我正在尝试从li
li
组中识别div
元素
<div id="group">
<li></li>
<li></li>
<li></li>
</div>
它非常简单,我可以给每个li
一个唯一的id,这个问题就结束了。像
var listItem1,2,3 = document.getElementById('liItem1,2,3') etc
listItem1,2,3.addEventListener('click',function);
这对于1,2或3个元素来说可能很方便,但这一切都是静态的,当它开始扩展时它不再可能,而是我试图利用NodeList
。
var nodeList = document.getElementById('group').getElementsByTagName('li');
现在我将有一个NodeList with li 0, li 1, li 2
问题来了,因为我不知道如何追踪被点击的li
。
nodeList.addEventListener('click',function);
不会在这里工作,因为它知道在这里点击了哪一个。
nodeList[0].addEventListener('click',function);
与上述解决方案相同。如何跟踪点击li
中的哪一个?只有普通/原始javascript
答案 0 :(得分:1)
要查找响应事件的元素的索引,我建议将事件处理委托给祖先(而不是将事件处理程序单独绑定到多个子元素):
// 'event' is passed in automagically (in non IE browsers, haven't tested IE):
function getIndexFrom(event){
// event.target is the element upon which the event was triggered:
var clicked = event.target,
// finding all the children of the parent of the clicked-element
// (could use 'this.children', as 'this' will be the 'ul' in this demo):
children = clicked.parentNode.children;
// iterating over those child elements:
for (var i = 0, len = children.length; i < len; i++){
// if the clicked element is the current element:
if (children[i] === clicked){
console.log('index is: ' + i)
// we return 'i' as the index:
return i;
}
}
// this shouldn't happen, assuming we're looking at the right group
// of elements, but it's there as an in-case and for debugging:
return false;
}
document.getElementById('group').addEventListener('click', getIndexFrom);
参考文献: