简体   繁体   中英

Get index <li> with jquery if click is on child element

I have a html list and i need to get index li when click is on its a child element.

I have this:

<ul>
<li><a>item 1</a></li>
<li><a>item 2</a></li>
<li><a>item 3</a></li>
</ul>

In other case i would have used

$('li').click(function() {
$(this).index();
});

But in this case i need get li index when click is on a, so i try:

$('li a').click(function() {
$(li).index();
});

I expect li index, but just get 0 on console.log

Get the parent of clicked anchor tag and find it's index from the array of lis .

 $('li a').click(function() { const lis = $('li'); const index = lis.index($(this).parent()); console.log(index); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li><a>item 1</a></li> <li><a>item 2</a></li> <li><a>item 3</a></li> </ul> 

You can use .closest() (in case some a is not the direct child of li , else .parent() is enough) in jquery to do this.

Demo:

 $('li a').click(function() { console.log($(this).closest('li').index()); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li><a>item 1</a></li> <li><a>item 2</a></li> <li><a>item 3</a></li> </ul> 

You can try with parent

 $('li a').click(function() { console.log($(this).parent().index()); }); 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <ul> <li><a>item 1</a></li> <li><a>item 2</a></li> <li><a>item 3</a></li> </ul> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM