How can I get the index of non-sibling elements in jquery?

HTML:

<ul> <li>Help</li> <li>me</li> <li>Stack</li> <li>Overflow!</li> </ul> <br> <ul> <li>Can</li> <li>I</li> <li>connect</li> <li>these?</li> </ul> 

Javascript / jQuery:

 $("li").live('click', function(){ alert($(this).index()); }); 

I put together a simple jsfilled page to help describe my problem: http://jsfiddle.net/T4tz4/

Currently pressing LI warns the index of the current UL group. I would like to know if it is possible to get a "global index", so clicking on "Can" returns an index value of 4.

Thanks, John

+4
source share
2 answers

Just put the 'li' selector inside index()

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

Live demo: http://jsfiddle.net/T4tz4/3/


http://api.jquery.com/index/

If the selector string is passed as argument, .index () returns an integer indicating the position of the source element relative to the elements corresponding to the selector.

+8
source

Here's the solution: http://jsfiddle.net/T4tz4/1/

 $("li").each(function(index) {$(this).data("index",index);}); $("li").live('click', function(){ alert($(this).data("index")); }); 
+4
source

Source: https://habr.com/ru/post/1338766/


All Articles