[英]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.我有一个很长的列表,需要获取其中每个 li 的索引。 Here's my html:
这是我的 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:我的 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.我的警报显示我的索引在返回 -1 时不起作用。 However I have the syntax correct (i think) becase the variables are using contain the right elements.
但是我的语法正确(我认为)因为变量使用包含正确的元素。 Here is output of the alert:
这是警报的 output:
ul id: myUl
the li: test
index: -1
So why is it returning -1???那么为什么它返回-1???
index()
returns the index of an element within a set of elements, not within the children of the first element in the set. index()
返回一个元素在一组元素中的索引,而不是在该集合中第一个元素的子元素中。
Your theUl
variable contains exactly one element – the <ul>
tag.您的
theUl
变量只包含一个元素 - <ul>
标记。 Since this set doesn't have your <li>
tag, index()
returns -1
.由于该集合没有您的
<li>
标记,因此index()
返回-1
。
You can write theUl.children().index(thisLi)
to find the index of the <li>
in the <ul>
's children.您可以编写
theUl.children().index(thisLi)
以在<ul>
的孩子中查找<li>
的索引。
You can also just write thisLi.index()
to return the index of the <li>
within it's immediate parent.您也可以只编写
thisLi.index()
来返回<li>
在其直接父级中的索引。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.