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


JQuery index()用法及代碼示例


index()是jQuery中的內置方法,用於返回指定元素相對於選擇器的索引。
用法:

$(selector).index(element)

參數:它接受可選參數“element”,該參數用於獲取元素的位置。
返回值:它返回一個整數,該整數表示指定元素的索引。

jQuery代碼顯示index()函數的工作方式:

代碼1:
<!DOCTYPE html> 
<html> 
  
<head> 
    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
    <script> 
        <!--jQuery code to demonstrate index function -->
  
        // document ready 
        $(document).ready(function() { 
            // if the list is clicked 
            $("li").click(function() { 
                // index()  
                // to return the index of the clicked 
                // element of the list 
                document.getElementById("demo").innerHTML = "Clicked Index " 
                                                            + $(this).index(); 
            }); 
        }); 
    </script> 
</head> 
  
<body> 
  
    <p>Click on the elements of the list to display their index 
       number with respect to the other elements in the list.</p> 
  
    <ul> 
        <li>Geeks</li> 
        <li>for</li> 
        <li>Geeks</li> 
    </ul> 
  
    <p id="demo"></p> 
</body> 
  
</html>

輸出:
在單擊列表上的任何元素之前


Click on the elements of the list to display their index number with respect to the other elements in the list.

  • 極客
  • 對於
  • 極客

點擊“for”-

Click on the elements of the list to display their index number with respect with the other elements in the list.

  • 極客
  • 對於
  • 極客
點擊索引1

代碼2:

<!DOCTYPE html> 
<html> 
  
<head> 
    <script 
    src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"> 
    </script> 
    <script> 
        <!--jQuery code to demonstrate index function -->
  
        // document ready 
        $(document).ready(function() { 
            // if the list is clicked 
            $("li").click(function() { 
                // index()  
                // to return the index of the clicked 
                // element of the list 
                document.getElementById("demo").innerHTML = "Clicked Index " 
                                    + $($(".myclass")).index($("#id")); 
            }); 
        }); 
    </script> 
</head> 
  
<body> 
  
    <p>Click on the elements of the list to display their index 
       number with respect with the other elements in the list.</p> 
  
    <ul> 
        <li>Geeks</li> 
        <li class="myclass">for</li> 
        <li class="myclass" id="id">Geeks</li> 
    </ul> 
  
    <p id="demo"></p> 
</body> 
  
</html>

輸出:
在單擊列表上的任何元素之前,

Click on the elements of the list to display their index number with respect with the other elements in the list.

  • 極客
  • 對於
  • 極客

點擊列表中的任何元素後,

Click on the elements of the list to display their index number with respect with the other elements in the list.

  • 極客
  • 對於
  • 極客
點擊索引1

相關用法


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