.even()


.even()傳回: jQuery

說明: 將匹配元素的集合縮小到集合中從 0 開始編號的偶數元素。

  • 新增版本: 3.5.even()

    • 此方法不接受任何參數。

給定一個表示 DOM 元素集合的 jQuery 物件,.even() 方法會從該集合中的偶數元素建構一個新的 jQuery 物件。從 0 開始計數!

考慮一個包含簡單清單的網頁

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" ).even().css( "background-color", "red" );

此呼叫的結果是第一、第三和第五個項目有紅色背景。

範例

在清單中突顯偶數項目。

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
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>even demo</title>
<style>
.highlight {
background-color: yellow;
}
</style>
<script src="https://code.jquery.com/jquery-3.7.0.js"></script>
</head>
<body>
<ul>
<li>Look:</li>
<li>This is some text in a list.</li>
<li>This is a note about it.</li>
<li>This is another note about it.</li>
</ul>
<script>
$( "ul li" ).even().addClass( "highlight" );
</script>
</body>
</html>

示範