我有一个html,看起来像:
<div class="info">
<p>132 Purple Grove</p>
<p>Albany, Texas 76801</p>
<p class="phone">
<span>Phone: (111) 111-1111</span>
</p>
<p class="fax">Fax: (111) 111-1111</p>
</div>使用cheerio,我想得到一个数组,所有的p元素都没有“电话”或“传真”类。Cheerio没有.not函数,所以我尝试用如下的过滤器复制它:
var addresslines=$(.info).children('p').filter(function(n){
if(!$(n).hasClass('phone') && !$(n).hasClass('fax')){
return n;
}
});因此,我得到了以下数组(删除了换行符),它过滤掉第一个元素,而其他元素则不受影响。我似乎不明白为什么..。
结果:
0 Albany, Texas 76801
1 Phone: (111) 111-1111
2 Fax: (111) 111-1111 小提琴:http://jsfiddle.net/2cPLK/
发布于 2014-07-22 01:27:00
当filter接受一个函数作为参数时,它用两个参数填充该函数;第一个参数是索引,第二个参数是元素。因此,当前您掌握的变量n是一个整数,而不是一个元素。
var addresslines=$('.info').children('p').filter(function(n, el){
if(!$(el).hasClass('phone') && !$(el).hasClass('fax')){
return el;
}
});工作小提琴
发布于 2014-07-22 01:38:35
filter的第一个参数是索引,而不是元素,因此您应该将代码更改为:
var addresslines=$(.info).children('p').filter(function(n){
if(!$(this).hasClass('phone') && !$(this).hasClass('fax')){
return true;
}
});工作小提琴:http://jsfiddle.net/2cPLK/1/
https://stackoverflow.com/questions/24877398
复制相似问题