jQuery选择器与filter() [英] jQuery selector vs filter()
问题描述
给出以下标记
<ul class="list">
<li>first item</li>
<li class="item">second item</li>
<li>third item</li>
</ul>
这两个表达式中的哪一个最好选择第二个li?
Which one these 2 expressions is better to select the second li?
$("ul li.item")
或
$("ul li").filter(".item")
这不是一个很好的例子,因为它太简单了(我知道我可以做$(".item")
,但是总的来说,我应该使用复杂的选择器还是过滤器功能?
This is not a very good example because it's too simple (I know I could be doing $(".item")
, but in general, should I be using complex selectors or the filter function?
编辑:如果第一个效率更高,什么时候/最好使用过滤器功能?
EDIT: If the first is more efficient, when is it appropriate / best to use the filter function?
推荐答案
第一个更快:
$("ul li.item")
这是完全正确的,因为它是等效的,但是没有两次运行选择器引擎(Sizzle)才能到达那里.
This is true simply because it's equivalent, but isn't running the selector engine (Sizzle) twice to get there.
用于您使用 .filter()
...好,当您需要过滤当前集合时,或者当您需要复杂的过滤器时.例如,如果您想链接但不想再次选择集合:
For your edit: You use .filter()
...well, when you need to filter the current set, or when you need a complex filter. For example if you wanted to chain but not select the set again:
$("ul li").addClass('everyItem').filter('.item').fadeOut();
或者是复杂的过滤器:
$("ul li").filter(function() {
return $.data(this, 'hasSomething');
}).fadeOut();
很多用途的过滤器,实际上取决于哪种情况最适合.就像您的问题一样,$(selector).filter(selector)
...我想不出您是否希望在单个选择器上使用它,如果可能的话.在我头顶上唯一无法完成的情况是 :has()
和 :not()
包装.
There are many uses of filter, it really depends on the situation as to what fits best. As pertains to your question though, $(selector).filter(selector)
...I can't think of a case where you'd want this over a single selector if it's at all possible. The only case off the top of my head you can't do that is a complex :has()
and :not()
wrapping.
这篇关于jQuery选择器与filter()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!