.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 的背景設為紅色。請注意,提供的索引是從 0 開始,且是指元素在 jQuery 物件中的位置,而非在 DOM 樹中的位置。

提供負數表示從集合的結尾開始的位置,而非從開頭開始。例如

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

這次清單項目 4 會變成紅色,因為它是集合結尾的倒數第二個。

如果在指定的從 0 開始的索引找不到元素,此方法會建構一個新的 jQuery 物件,其中有一個空的集合和一個長度為 0 的 length 屬性。

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

示範