:eq() 選擇器


eq 選擇器版本已棄用:3.4

說明: 選取符合條件組中索引為 n 的元素。

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

    index: 要符合條件的元素的 0 為基底索引。

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

    indexFromEnd: 要符合條件的元素的 0 為基底索引,從最後一個元素開始倒數。

自 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.jquery.com/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():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-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.jquery.com/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>

示範