jQuery :first vs. .first()

前端 未结 4 1738
夕颜
夕颜 2020-11-29 01:12

The .first() method was added in jQuery 1.4.

The :first selector has been around since 1.0.

From the docs:

:first

4条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-29 01:52

    .first() can be used to select the first element in a jQuery collection.

    Basically, it avoids having to do a new query or break the chain in situations when you need to work on a collection and then exclusively on the first element.

    Actually, one of the most costly operations you can do in jQuery is a query. The less you do, the better it is...

    One example I can think of right now is an image gallery script where your first image is always the default active one, yet you need to attach an event handler on each image...

    $('#gallery img').click(myFunc).first().addClass('active');
    
    // Instead of
    $('#gallery img').click(myFunc);
    $('#gallery img:first').addClass('active');
    

    .first() is also syntactic sugar for something that exists since 1.1.2... .eq(0):

    $('#gallery img').click(myFunc).eq(0).addClass('active');
    

    in fact, that's how it is implemented in jQuery itself:

    first: function() {
      return this.eq( 0 );
    }
    

提交回复
热议问题