Usage analysis of index of in jQuery


This article illustrates the use of index() in jQuery. Share with you for your reference. Specific methods are as follows:

Now here’s the question: if there are more than N items in the list, I want to know which one I clicked and how to get it?

JQuery has an index() method for this:

index(subject)

This method searches for elements that match the object represented by the parameter and returns the index value of the corresponding element.

If a match is found, return from 0; If no matching element is found, -1 is returned.

However, the example provided in the API seems to be wrong. The example is as follows:

<ul>
  <li><a href="#nogo"> Here is a sequence </a></li>
  <li><a href="#nogo"> Here is a sequence </a></li>
  <li><a href="#nogo"> Here is a sequence </a></li>
  <li><a href="#nogo"> Here is a sequence </a></li>
  <li><a href="#nogo"> Here is a sequence </a></li>
  <li><a href="#nogo"> Here is a sequence </a></li>
</ul>

So as you can see, this is an unordered list and I’m going to click on any list item and I’m going to ask for a sequence of items and what happens?

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!