I have an unordered list, with a couple list-items inside. Inside each of those is a link. What I want to do is find the position of the list-item when someone clicks the link inside it.
For example, if someone clicks the link inside the 3rd list-item, it gives me a value of 3.
开发者_开发问答I already have the click part, just need to figure out how to get the position of the list-item
Javascript only
Here's a simple live example that does what you want (except the list does not have links)
http://jsfiddle.net/8k926/2/
In the "Result" box click on one of the list items. It will have a handler that pops up its sequence number.
The Javascript code is the following
var els = document.getElementsByTagName('li');
Array.prototype.forEach.call(els,function(el,i){
el.addEventListener('click', function(){alert(i);}, false);
}) ;
Although els
is array-like, it does not have a forEach
method. We get around that by using the Array.prototype.forEach
method.
Update: Here's a second live example that narrows things down to a specific list, as opposed to all list items.
http://jsfiddle.net/8k926/3/
Also, as a commenter points out, forEach
is not universally supported, but it is used here to simplify the code.
// A ul only has li childnodes.
count 'backwards' from the li element containing the clicked link.
var count= 1, li= linkelement;
while(li && li.nodeName!= 'LI') li= li.parentNode; // get the li element
while(li){
li= li.previousSibling;
// count previous li elements
++count;
}
alert(count)// firstChild is 1, not 0
Using jQuery: add a click event to all links in lists which firstly selects the parent 'li' element of the link, then walks backwards selecting each 'li' element until there are no more to select and an empty jquery object is returned. Should be easy to adapt.
$('li a').click(function(){
$node = $(this).parent();
result = 0;
while ($node.length > 0){
result++;
$node = $node.prev();
}
alert(result);
return false;
});
精彩评论