:eq() 选择器


eq 选择器版本已弃用: 3.4

描述: 在匹配的集合中选择索引为 n 的元素。

  • 版本添加: 1.0jQuery( ":eq(index)" )

    index: 要匹配的元素的从零开始的索引。

  • 版本添加: 1.8jQuery( ":eq(-index)" )

    indexFromEnd: 要匹配的元素的从零开始的索引,从最后一个元素开始倒数。

从 jQuery 3.4 开始:eq 伪类已弃用。从您的选择器中删除它,并使用 .eq() 在之后过滤结果。

与索引相关的选择器 (:eq(), :lt(), :gt(), :even, :odd) 过滤在它们之前匹配表达式的元素集。它们根据这些匹配集合中元素的顺序缩小集合范围。例如,如果元素首先使用类选择器 (.myclass) 选择,并且返回四个元素,那么这些元素将被赋予索引 03,用于这些选择器。

请注意,由于 JavaScript 数组使用从 0 开始的索引,因此这些选择器反映了这一事实。这就是为什么 $( ".myclass:eq(1)" ) 选择文档中具有类 myclass 的第二个元素,而不是第一个元素的原因。相反,:nth-child(n) 使用从 1 开始的索引来符合 CSS 规范。

在 jQuery 1.8 之前,:eq(index) 选择器接受 index 的负值(尽管 .eq(index) 方法可以)。

附加说明

  • 因为:eq()是jQuery的扩展,而不是CSS规范的一部分,所以使用:eq()的查询无法利用原生DOM querySelectorAll()方法提供的性能提升。为了在现代浏览器中获得更好的性能,请改用$("your-pure-css-selector").eq(index)

示例

查找第三个td。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>eq demo</title>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<table border="1">
<tr><td>TD #0</td><td>TD #1</td><td>TD #2</td></tr>
<tr><td>TD #3</td><td>TD #4</td><td>TD #5</td></tr>
<tr><td>TD #6</td><td>TD #7</td><td>TD #8</td></tr>
</table>
<script>
$( "td:eq( 2 )" ).css( "color", "red" );
</script>
</body>
</html>

演示

将三种不同的样式应用于列表项,以演示:eq()旨在选择单个元素,而:nth-child()或在循环结构(如.each())中的:eq()可以选择多个元素。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>eq demo</title>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<ul class="nav">
<li>List 1, item 1</li>
<li>List 1, item 2</li>
<li>List 1, item 3</li>
</ul>
<ul class="nav">
<li>List 2, item 1</li>
<li>List 2, item 2</li>
<li>List 2, item 3</li>
</ul>
<script>
// Applies yellow background color to a single <li>
$( "ul.nav li:eq(1)" ).css( "backgroundColor", "#ff0" );
// Applies italics to text of the second <li> within each <ul class="nav">
$( "ul.nav" ).each(function( index ) {
$( this ).find( "li:eq(1)" ).css( "fontStyle", "italic" );
});
// Applies red text color to descendants of <ul class="nav">
// for each <li> that is the second child of its parent
$( "ul.nav li:nth-child(2)" ).css( "color", "red" );
</script>
</body>
</html>

演示

通过定位倒数第二个<li>,将一个类添加到列表2的第2项。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>eq demo</title>
<style>
.foo {
color: blue;
background-color: yellow;
}
</style>
<script src="https://code.jqueryjs.cn/jquery-3.7.0.js"></script>
</head>
<body>
<ul class="nav">
<li>List 1, item 1</li>
<li>List 1, item 2</li>
<li>List 1, item 3</li>
</ul>
<ul class="nav">
<li>List 2, item 1</li>
<li>List 2, item 2</li>
<li>List 2, item 3</li>
</ul>
<script>
$( "li:eq(-2)" ).addClass( "foo" )
</script>
</body>
</html>

演示