jQuery selector vs filter()

前端 未结 1 584
北恋
北恋 2021-01-18 03:14

Given the following markup

  • first item
  • second item
  • t
1条回答
  •  囚心锁ツ
    2021-01-18 03:29

    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.

    0 讨论(0)
提交回复
热议问题