jQuery index()的例子

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. * Geeks * for * Geeks

在点击 “为 “之后-



Click on the elements of the list to display their index number with respect with the other elements in the list. * Geeks * for * Geeks Clicked Index 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. * Geeks * for * Geeks

在点击列表中的任何元素后–



Click on the elements of the list to display their index number with respect with the other elements in the list. * Geeks * for * Geeks Clicked Index 1

Python教程

Java教程

Web教程

数据库教程

图形图像教程

大数据教程

开发工具教程

计算机教程