I have a long list and need to get the index of every li wit开发者_运维问答hin 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 & 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
精彩评论