I have the following HTML page:
<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:
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.
“你的代码是正确的”
try to use:
if (aElements[i] === sender)
instead of
if (aElements[i] == sender)
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.
Jquery can help using prevAll()
$(document).on("click","li",function(){
var index=$(this).prevAll();
alert(index);
});
Are you sure GetIndex function gets executed on click event on anchor tag?
Try by giving href attribute to anchor tag. You can write either
<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/
The modern way to find index of element
[...el.parentNode.children].indexOf(el)
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.