访问jQuery中类的第二个成员

Accessing the 2nd member of a class in jQuery?

本文关键字:第二个 成员 jQuery 访问      更新时间:2024-01-27

我有一堆div,它们属于一个特定的类,比如tab。语义结构看起来像这样:

<div class = "tabs" >_______</div>
<div class = "tabs" >_______</div>
<div class = "tabs" >_____</div>

很容易访问类似的div的第一个和最后一个元素

$('.tabs:first') or
$('.tabs:last')

但是到了第二个(假设里面有多个其他div,那么除了第一个或最后一个之外的所有div)似乎会给我带来语法错误,比如:

$('.tabs:second') or $('.tabs:third')不能预期地工作。

有人能指出这里出了什么问题吗?

尝试使用eq()选择器,注意索引是基于零的:

$(".tabs:eq(1)");

有两种方法可以做到这一点,使用.eq()方法或:eq()选择器。

.eq()方法:

jQuery文档建议您这样做的方法是使用.eq()方法。

// eq() is zero-based, so this would get the second element
$('.tabs').eq(1)

一个方便的特性是.eq()也可以取负数,这会导致函数从末尾开始。

// This would take the second element from the end
$('.tabs').eq(-2);

:eq()选择器

jQuery还提供了一个:eq()选择器,其工作方式与.eq()方法基本相同。所以你也可以这样做:

$('.tabs:eq(1)')

请注意,尽管这是可行的,但最好使用.eq()方法而不是选择器。该方法在现代浏览器中具有更好的性能,并且:eq()选择器不支持负数,因此它在一定程度上受到了限制。

查看jQuery :first选择器文档:http://api.jquery.com/first-selector/

您会注意到这是一个jQuery扩展,而不是CSS规范的一部分。此外,:first等价于:eq(0),这意味着如果你想获得第二个元素,你可以用:eq(1)来完成。

如果您不需要CSS选择器中的过滤器,您可以简单地使用.eq方法获取元素,如下所示:

$('.tabs').eq(0) // get the first element
$('.tabs').eq(1) // get the second element
$('.tabs').eq(2) // get the third element
$('.tabs').eq(-2) // get the second to last element
$('.tabs').eq(-1) // get the last element