示例
保留带有select类的元素
HTML 代码:
<p>Hello</p><p>Hello Again</p><p class=”selected”>And Again</p>
jQuery 代码:
$(“p”).filter(“.selected”)
结果:
[ <p class=”selected”>And Again</p> ]
保留第一个以及带有select类的元素
HTML 代码:
<p>Hello</p><p>Hello Again</p><p class=”selected”>And Again</p>
jQuery 代码:
$(“p”).filter(“.selected, :first”)
结果:
[ <p>Hello</p>, <p class=”selected”>And Again</p> ]
————————————————————————————————————–
filter(fn)
筛选出与指定函数返回值匹配的元素集合
这个函数内部将对每个对象计算一次 (正如 ‘$.each’). 如果调用的函数返回false则这个元素被删除,否则就会保留。
Removes all elements from the set of matched elements that does not match the specified function.
The function is called with a context equal to the current element (just like ‘$.each’). If the function returns false, then the element is removed – anything else and the element is kept.
返回值
jQuery
参数
fn (Function) : 传递进filter的函数
示例
保留子元素中不含有ol的元素。
HTML 代码:
<p><ol><li>Hello</li></ol></p><p>How are you?</p>
jQuery 代码:
$(“p”).filter(function(index) {
return $(“ol”, this).length == 0;
});
结果:
[ <p>How are you?</p> ]
————————————————————————————————————–
is(expr)
用一个表达式来检查当前选择的元素集合,如果其中至少有一个元素符合这个给定的表达式就返回true。
如果没有元素符合,或者表达式无效,都返回’false’. ‘filter’ 内部实际也是在调用这个函数,所以,filter()函数原有的规则在这里也适用。










