.odd()


.odd()傳回: jQuery

說明: 將匹配元素的集合縮減為集合中從 0 開始編號的奇數元素。

  • 新增版本: 3.5.odd()

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

針對表示一組 DOM 元素的 jQuery 物件,.odd() 方法會從該組中的奇數元素建構一個新的 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" ).odd().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>odd 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" ).odd().addClass( "highlight" );
</script>
</body>
</html>

示範