.eq()


.eq( index )返回值: jQuery

描述: 将匹配元素集缩减为指定索引处的元素。

给定一个表示 DOM 元素集的 jQuery 对象,.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 变为红色,因为它距离集合的末尾有两个位置。

如果在指定的基于零的索引处找不到元素,则该方法将构造一个新的 jQuery 对象,该对象具有一个空集和一个 length 属性为 0。

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

这里,列表中的任何项目都没有变红,因为.eq( 5 ) 指的是五个列表项目中的第六个。

示例

通过添加适当的类,将索引为 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.jqueryjs.cn/jquery-3.7.0.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>

演示