当前位置: 首页>>代码示例 >>用法及示例精选 >>正文


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。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。