jQuery:第一与.first() [英] jQuery :first vs. .first()

查看:93
本文介绍了jQuery:第一与.first()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

.first()方法是在jQuery 1.4中添加的.

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

:first选择器从1.0开始就存在.

The :first selector has been around since 1.0.

从文档中

:first

:first伪类等效于:eq(0).也可以写为:lt(1).尽管此元素仅匹配一个元素,但:first-child可以匹配多个元素:每个父元素一个.

The :first pseudo-class is equivalent to :eq(0). It could also be written as :lt(1). While this matches only a single element, :first-child can match more than one: One for each parent.

.first()

给出一个代表一组DOM元素的jQuery对象,.first()方法从第一个匹配的元素构造一个新的jQuery对象.

Given a jQuery object that represents a set of DOM elements, the .first() method constructs a new jQuery object from the first matching element.


.first()似乎是一个返回另一个jQuery对象的过滤器,而:first只是一个选择器.


It seems that .first() is a filter that returns another jQuery object, while :first is just a selector.

但是,它们都可以用来完成同一件事.

But, they can both be used to accomplish the same thing.

那么,什么时候应该使用一个而不是另一个?表现?请提供示例.

So, when should one be used instead of the other? Performance? Please provide examples.

推荐答案

.first()可用于选择jQuery集合中的第一个元素.

.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.

实际上,您可以在jQuery中执行的最昂贵的操作之一就是查询.做得越少越好...

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()还是从1.1.2开始存在的语法糖... .eq(0):


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

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

实际上,这就是在jQuery本身中实现的方式:

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

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

这篇关于jQuery:第一与.first()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆