我想在 <li>
中找到被点击元素的编号容器。 (例如,点击的元素是第 3 个子元素。)
到目前为止我有这段代码:
window.onload = function ()
{
var dropDown = document.getElementsByTagName("nav")[0].getElementsByTagName("ul")[0].getElementsByTagName("li")[3];
dropDown.addEventListener('click', hide, false);
function hide(e) {
// Find out the number of the n-th child element you clicked instead of hiding it
e.target.style.visibility = 'hidden';
}
}
有没有办法找出我点击了哪个 child ?
最佳答案
我可能会误解,但这不就是indexOf()
吗?是吗?
var els = el.parentNode.children; // or .childNodes if you want TextNodes
return [].indexOf.call(els, el);
所以在事件处理程序中:
function(e) {
var el = e.target;
var els = el.parentNode.children; // or .childNodes if you want TextNodes
return [].indexOf.call(els, el);
}
自 parentNode.children
/parentNode.childNodes
不返回 Array
,而是一个 NodeList
(或类似),indexOf()
方法不可用。两个修复:
- 首先创建一个
Array
来自NodeList
然后调用indexOf
:arr = [].slice.call(children)
这意味着:Array.prototype.slice.call(children, 0)
这叫Array
的slice()
不同的方法this
上下文(如果您不知道那是什么意思,请阅读 call/apply/this)。然后:arr.indexOf(el)
- 或者立即在 NodeList 上使用相同的技巧。如果
slice
作品,indexOf
也应该工作:Array.prototype.indexOf.call(children, el)
或更短:[].indexOf.call(children /*this*/, el /*arg1*/)
- 我的最爱:
HTMLCollection.prototype.indexOf = NodeList.prototype.indexOf = Array.prototype.indexOf
瞧,现在你可以调用indexOf
直接在children
.不过,这是非常不受欢迎的:扩展 native 对象显然是一件坏事(TM)。
如果你不知道怎么做,那一切都是神奇的this
在 JS 中工作(就像魔术一样!)以及如何 Function.prototype.call()
有效。
关于javascript - 找出我刚刚点击了哪个子元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23642588/