jQuery雜項index()方法



jQuery中的index()方法用於查詢元素在其同級元素中的索引位置。

它通常用於確定元素在一組匹配元素中的位置。此方法返回一個整數,表示元素的索引位置,從0開始。如果找不到元素,則返回-1。

語法

以下是獲取(相對於其同級元素的第一個匹配選擇元素的索引位置)的此方法的語法:

$(selector).index()

以下是獲取(相對於選擇器的元素的索引位置)的此方法的語法:

$(selector).index(element)

引數

以下是上述語法的描述:

  • element(可選):一個DOM元素、一個jQuery物件或一個表示要查詢的元素的選擇器字串。

示例1

在下面的示例中,我們使用jQuery雜項index()方法來獲取被點選的列表項在其同級元素中的索引位置:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            $("li").click(function(){
                var index = $(this).index();
                alert("Index of clicked list item: " + index);
            });
        });
    </script>
</head>
<body>
    <ul>
        <li>Item 1</li>
        <li>Item 2</li>
        <li>Item 3</li>
        <li>Item 4</li>
    </ul>
</body>
</html>

執行上述程式後,點選項的索引值將透過alert顯示。

示例2

在這裡,我們檢索一組匹配元素中特定元素的索引位置:

<html>
<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script>
        $(document).ready(function(){
            var listItems = $("li");
            var specificItem = $("#item3");
            var index = listItems.index(specificItem);
            alert("Index of the specific item: " + index);
        });
    </script>
</head>
<body>
    <ul>
        <li id="item1">Item 1</li>
        <li id="item2">Item 2</li>
        <li id="item3">Item 3</li>
        <li id="item4">Item 4</li>
    </ul>
</body>
</html>

執行上述程式後,將檢索id="item3"的元素,並透過alert顯示。

jquery_ref_miscellaneous.htm
廣告
© . All rights reserved.