:eq() 选择器

eq selector

描述:在匹配集合内部选择位于索引n的元素。

  • 增补版本:1.0jQuery( ":eq(index)" )

    index: 要匹配元素的基于零的索引。

  • 增补版本:1.8jQuery( ":eq(-index)" )

    indexFromEnd: 要匹配的元素的基于零的索引,从最后一个元素开始往回计数。

索引相关的选择器(: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()查询不能利用原生DOMquerySelectorAll()方法提供的性能提升。欲在现代浏览器中取得较好的性能,请用$("your-pure-css-selector").eq(index)代替。

示例:

找到第3个id。

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.jquery.com/jquery-1.10.2.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():eq()在一个循环构造中,譬如在.each()中可以选择多个元素。

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.jquery.com/jquery-1.10.2.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.jquery.com/jquery-1.10.2.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>

演示: