jQuery :odd 選擇器



jQuery 中的 :odd 選擇器用於選擇匹配元素集中索引為奇數的元素。索引是從零開始的,這意味著第一個元素的索引為 0,第二個元素的索引為 1,依此類推。

注意:如果要選擇索引為偶數的元素,需要使用 :even 選擇器。

語法

以下是 jQuery :odd 選擇器的語法:

$("selector:odd")

引數

以下是上述語法的解釋:

  • selector: 這是一個 CSS 選擇器。它指定選擇元素的條件。例如
  • "div" 選擇所有 <div> 元素。

  • ".class" 選擇所有具有類 "class" 的元素。

  • "#id" 選擇 id 為 "id" 的元素。

  • odd: 過濾匹配的集合,只包含索引為奇數的元素。

示例 1

在下面的示例中,我們演示了 jQuery :odd 選擇器的基本用法:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        $("button").click(function(){
            $("li:odd").css("background-color", "grey");
        })
    });
</script>
</head>
<body>
<ul>
  <li>Even (index: 0)</li>
  <li>Odd (index: 1)</li>
  <li>Even (index: 2)</li>
  <li>Odd (index: 3)</li>
  <li>Even (index: 4)</li>
</ul>
<button>Click</button>
</body>
</html>

單擊按鈕後,:odd 選擇器將選擇所有索引為奇數的列表元素,並將其背景顏色突出顯示為灰色。

示例 2

在下面的示例中,我們使用 ":odd" 選擇器隱藏索引為奇數的 <div> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
      $("button").click(function(){
        $("div:odd").hide();
      })
    });
  </script>
</head>
<body>
<div>Even Div (Index: 0)</div>
<div>Odd Div (Index: 1)</div>
<div>Even Div (Index: 2)</div>
<div>Odd Div (Index: 3)</div>
<div>Even Div (Index: 4)</div>
<button>Click</button>
</body>
</html>

單擊按鈕後,所有索引為奇數的 div 元素都將被隱藏。

jquery_ref_selectors.htm

廣告
© . All rights reserved.