jQuery :even 選擇器



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

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

語法

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

$("selector:even")

引數

以下是上述語法的解釋:

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

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

  • "#id" 選擇具有 id "id" 的元素。

  • even: 篩選匹配的集合,僅包含索引為偶數的元素。

示例 1

在以下示例中,我們使用 :even 選擇器來選擇索引為偶數的列表項:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
        $("button").click(function(){
            $("li:even").css("background-color", "yellow");
        })
    });
</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>

單擊按鈕後,索引為偶數的列表項將以黃色背景色突出顯示。

示例 2

在此示例中,我們使用 ":even" 選擇器隱藏索引為偶數的 <div> 元素:

<html>
<head>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script>
    $(document).ready(function() {
      $("button").click(function(){
        $("div:even").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
廣告