Home >Web Front-end >JS Tutorial >Usage analysis of index() in jQuery_jquery
This article explains the usage of index() in jQuery with examples. Share it with everyone for your reference. The specific method is as follows:
Now I have a question: If there are N number of list items in the list, I want to know which one I clicked and how to retrieve it?
For this, jQuery provides an index() method:
index(subject)
This method searches for elements matching the object represented by the parameter and returns the index value of the corresponding element.
If a matching element is found, the return starts from 0; if no matching element is found, -1 is returned.
But the examples provided in the API seem wrong. The examples are as follows:
<ul> <li><a href="#nogo">这里是一个序列</a></li> <li><a href="#nogo">这里是一个序列</a></li> <li><a href="#nogo">这里是一个序列</a></li> <li><a href="#nogo">这里是一个序列</a></li> <li><a href="#nogo">这里是一个序列</a></li> <li><a href="#nogo">这里是一个序列</a></li> </ul>
As shown above, this is an unordered list. What if I want to click on any list item and get the sequence of the item?
The implementation method is as follows:
$(document).ready(function(){ $("#act li").click(function(){ alert( $( "#act li" ).index( $(this)[0] ) ); }) })
Here:
$( "#act li" ).index( $(this)[0] )
Very important!