.eq()

.eq( index )返回类型:jQuery

描述:把匹配的元素集合缩小到指定索引的那一个。

  • 增补版本:1.1.2.eq( index )

    • index
      类型:Integer
      一个整型数,指示了元素基于0的位置/
  • 增补版本:1.4.eq( indexFromEnd )

    • indexFromEnd
      类型:Integer
      一个整型数,指示了元素基于0的位置,从集合中最后一个元素开始计数。

给定一个jQuery对象,代表一些DOM元素,.eq()方法根据集合中的一个元素构造了一个新的jQuery对象。提供的索引标识了集合中的元素的位置。

请琢磨一个带有简单列表的网页:

1
2
3
4
5
6
7
<ul>
<li>list item 1</li>
<li>list item 2</li>
<li>list item 3</li>
<li>list item 4</li>
<li>list item 5</li>
</ul>

我们可以将此方法应用于列表项的集合:

1
$( "li" ).eq( 2 ).css( "background-color", "red" );

此调用的结果是项目3变红色背景。请注意,受支持的索引是基于零的,引用到元素在jQuery对象中的位置,而不是在DOM树中的位置。

提供一个负数,指示从集合末尾开始的位置,而不是从开头开始的位置。例如:

1
$( "li" ).eq( -2 ).css( "background-color", "red" );

这次列表项4变红了,因为它是集合中倒数第二个。

如果在指定的基于0的索引中找到不元素,此方法将构造一个新jQuery对象,带有空的集合以及length为零。

1
$( "li" ).eq( 5 ).css( "background-color", "red" );

这里,没有一个列表项变红,因为.eq( 5 )指示了5个列表项的第6项。

示例:

通过添加适当的类,把带有索引2的div变蓝。

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>eq demo</title>
<style>
div {
width: 60px;
height: 60px;
margin: 10px;
float: left;
border: 2px solid blue;
}
.blue {
background: blue;
}
</style>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<div></div>
<script>
$( "body" ).find( "div" ).eq( 2 ).addClass( "blue" );
</script>
</body>
</html>

演示: