當前位置: 首頁>>代碼示例 >>用法及示例精選 >>正文


JQuery odd()用法及代碼示例


jQuery odd() 方法用於從所選元素中選擇奇數索引元素。

用法:

$(selector).odd()

返回值:它返回所選元素中的奇數索引元素。

範例1:此示例選擇奇數索引列表元素。


<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        jQuery odd() method
    </title>
  
    <script src=
"https://code.jquery.com/jquery-3.5.0.js">
    </script>
      
    <style>
        li {
            width:150px;
            margin:0 auto;
        }
  
        .highlight {
            background-color:green;
        }
    </style>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
      
    <p id="GFG_UP"></p>
      
    <ul>
        <li>GFG_0</li>
        <li>GFG_1</li>
        <li>GFG_2</li>
        <li>GFG_3</li>
        <li>GFG_4</li>
    </ul>
    <br>
      
    <button onclick="Geeks()">
        Click here
    </button>
      
    <p id="GFG_DOWN"></p>
      
    <script>
        var elUp = document.getElementById("GFG_UP");
        var elDown = document.getElementById("GFG_DOWN");
        elUp.innerHTML = "JQuery | odd() method";
          
        function Geeks() {
            $("ul li").odd().addClass("highlight");
            elDown.innerHTML = 
                "The odd elements are highlighted";
        } 
    </script>
</body>
  
</html>  

輸出:

範例2:這個例子檢查了奇數索引複選框。


<!DOCTYPE HTML>
<html>
  
<head>
    <title>
        jQuery odd() method
    </title>
  
    <script src=
"https://code.jquery.com/jquery-3.5.0.js">
    </script>
</head>
  
<body style="text-align:center;">
    <h1 style="color:green;">
        GeeksForGeeks
    </h1>
      
    <p id="GFG_UP"></p>
      
    GFG_0:<input type="checkbox" 
        id="GFG_0" value="GFG_0"><br>
  
    GFG_1:<input type="checkbox" 
        id="GFG_1" value="GFG_1"><br>
  
    GFG_2:<input type="checkbox" 
        id="GFG_2" value="GFG_2"><br>
  
    GFG_3:<input type="checkbox" 
        id="GFG_3" value="GFG_3"><br>
  
    GFG_4:<input type="checkbox" 
        id="GFG_4" value="GFG_4">
    <br><br>
      
    <button onclick="Geeks()">
        Click here
    </button>
      
    <p id="GFG_DOWN"></p>
      
    <script>
        var elUp = document.getElementById("GFG_UP");
        var elDown = document.getElementById("GFG_DOWN");
        elUp.innerHTML = "JQuery | odd() method";
          
        function Geeks() {
            $("input").odd().attr("checked", true);
            el_down.innerHTML = 
                "The odd elements are checked";
        } 
    </script>
</body>
  
</html>

輸出:




相關用法


注:本文由純淨天空篩選整理自PranchalKatiyar大神的英文原創作品 jQuery odd() Method。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。