jQuery :eq() 選擇器



目的::eq() 選擇器用於選擇匹配元素集中指定索引處的元素。索引:索引從 0 開始,這意味著第一個元素的索引為 0。用法:當您需要根據元素在組中的位置來定位特定元素時,它非常有用。返回值:返回一個包含指定索引處元素的 jQuery 物件。

語法

以下是 jQuery :eq() 選擇器的語法:

$(":eq(index)")

引數

以下是上述語法的描述:

  • index:要選擇的元素的基於零的索引。

示例 1

在下面的示例中,我們使用 jQuery :eq() 選擇器來選擇索引為“2”的段落元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("p:eq(2)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <p>Paragraph 1</p>
    <p>Paragraph 2</p>
    <p>Paragraph 3</p>
    <p>Paragraph 4</p>
</body>
</html>

執行上述程式後,索引為“2”的段落元素將以黃色背景突出顯示。

示例 2

在此示例中,我們選擇索引為“1”的列表項:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li:eq(1)").css("background-color", "yellow");
        });
    </script>
</head>
<body>
    <ul>
        <li>List Item 1</li>
        <li>List Item 2</li>
        <li>List Item 3</li>
        <li>List Item 4</li>
    </ul>
</body>
</html>

執行上述程式後,索引為“1”的列表項將以黃色背景突出顯示。

示例 3

在這裡,我們選擇索引為“3”的 <div> 元素:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            // Select and hide the fourth div element (index 3)
            $("div:eq(3)").hide();
        });
    </script>
</head>
<body>
    <div>Div 1</div>
    <div>Div 2</div>
    <div>Div 3</div>
    <div>Div 4</div>
</body>
</html>

執行上述程式後,選定的元素將以黃色背景突出顯示。

jquery_ref_selectors.htm
廣告