Home >Web Front-end >JS Tutorial >Usage analysis of index() in jQuery_jquery

Usage analysis of index() in jQuery_jquery

WBOY
WBOYOriginal
2016-05-16 16:36:561339browse

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn