Given the following markup
<ul class="list">
<li>first item</li>
<li class="item">second item</li>
<li>third item</li>
</ul>
Which one these 2 expressions is better to select the second li?
$("ul li.item")
or
$("ul li").filter(".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 开发者_如何学Python/ best to use the filter function?
The first is faster:
$("ul li.item")
This is true simply because it's equivalent, but isn't running the selector engine (Sizzle) twice to get there.
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();
Or a complex filter:
$("ul li").filter(function() {
return $.data(this, 'hasSomething');
}).fadeOut();
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.
精彩评论