使用 Javascript 获取 HTML ul 列表中的列表项索引
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4032654/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get list item index in HTML ul list using Javascript
提问by Boris
I have the following HTML page:
我有以下 HTML 页面:
<html>
<head>
<script type="text/javascript" src="JavaScript/Menu.js"></script>
</head>
<body>
<ul>
<li><a onclick="GetIndex(this)">One</a></li>
<li><a onclick="GetIndex(this)">Two</a></li>
<li><a onclick="GetIndex(this)">Three</a></li>
<li><a onclick="GetIndex(this)">Four</a></li>
</ul>
</body>
</html>
And the Menu.js javascript:
和 Menu.js javascript:
function GetIndex(sender)
{
var aElements = sender.parentNode.parentNode.getElementsByTagName("a");
var aElementsLength = aElements.length;
var index;
for (var i = 0; i < aElementsLength; i++)
{
if (aElements[i] == sender) //this condition is never true
{
index = i;
return index;
}
}
}
Why is the commented condition never met? How do I compare if the two HTML elements are equal in Javascript? Thanks for all the help.
为什么从不满足评论条件?如何比较两个 HTML 元素在 Javascript 中是否相等?感谢所有的帮助。
回答by xj9
"Your code is correct"
“你的代码是正确的”
回答by dareapersven
Old Post, but here is a quick function to do this:
旧帖子,但这里有一个快速功能可以做到这一点:
function nodeIndex(el) {
var i=0;
while(el.previousElementSibling ) {
el=el.previousElementSibling;
i++;
}
return i;
}
This should work with an element reference as the parameter. It basically just returns the number of previous siblings.
这应该使用元素引用作为参数。它基本上只是返回以前的兄弟姐妹的数量。
回答by Vin.X
try to use:
尝试使用:
if (aElements[i] === sender)
如果(aElements[i] === 发件人)
instead of
代替
if (aElements[i] == sender)
回答by Chinmayee G
Are you sure GetIndex function gets executed on click event on anchor tag?
你确定 GetIndex 函数在锚标签上的点击事件上执行吗?
Try by giving href attribute to anchor tag. You can write either
尝试将 href 属性赋予锚标记。你可以写
<a href="#" onclick="GetIndex(this)">One</a>
or
或者
<a href="javascript:void(0)" onclick="GetIndex(this)">One</a>
here is the working example http://jsfiddle.net/QfRSb/
回答by Jeffrey the Giraffe
Jquery can help using prevAll()
Jquery 可以帮助使用 prevAll()
$(document).on("click","li",function(){
var index=$(this).prevAll();
alert(index);
});

