简体   繁体   中英

Why can't I get the index of this li?

I have a long list and need to get the index of every li within it. Here's my html:

 <ul id="myUl" class="playlist playlist-one cf">

   <li id="test"><a href="#during-your-stay" class="playlist-link" >1.  Privacy &amp; Dignity for all</a>[00:34]</li>
   <li><a href="#during-your-stay" class="playlist-link" >2.  Medicines</a>[00:44]</li>
   <li><a href="#during-your-stay" class="playlist-link" >3.  Allergies</a>[00:25]</li>

</ul>

My jquery:

$(".playlist-link").click(function(){

    var thisLi=$(this).parent();
    var theUl= $(thisLi).parent();
    var index =theUl.index(thisLi);

    alert("ul id: " + theUl.attr('id') +"\n the li: " + thisLi.attr('id') +"\n index: "+index +"\n" )



});

My alert shows my index isn't working as it returns -1. However I have the syntax correct (i think) becase the variables are using contain the right elements. Here is output of the alert:

 ul id: myUl
 the li: test
 index: -1

So why is it returning -1???

index() returns the index of an element within a set of elements, not within the children of the first element in the set.

Your theUl variable contains exactly one element – the <ul> tag. Since this set doesn't have your <li> tag, index() returns -1 .

You can write theUl.children().index(thisLi) to find the index of the <li> in the <ul> 's children.

You can also just write thisLi.index() to return the index of the <li> within it's immediate parent.

http://api.jquery.com/index

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