javascript - 找出我刚刚点击了哪个子元素

标签 javascript

我想在 <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()方法不可用。两个修复:

  1. 首先创建一个Array来自 NodeList然后调用indexOf : arr = [].slice.call(children)这意味着:Array.prototype.slice.call(children, 0)这叫Arrayslice()不同的方法 this上下文(如果您不知道那是什么意思,请阅读 call/apply/this)。然后:arr.indexOf(el)
  2. 或者立即在 NodeList 上使用相同的技巧。如果slice作品,indexOf也应该工作:Array.prototype.indexOf.call(children, el)或更短:[].indexOf.call(children /*this*/, el /*arg1*/)
  3. 我的最爱: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/

相关文章:

javascript - 编剧自动滚动到无限滚动页面底部

javascript - 将 View 中声明的变量传递给 javascript

javascript - 将滚动条添加到 DataTable 的一侧(封装 DT)

javascript - nodejs - 过滤实时输出

javascript - 如何开发将 javascript 标签添加到商店中所有页面的 Bigcommerce 应用程序?

javascript - 尝试限制 div 移动时出现问题

javascript - 页面在 iPhone 中存在虚拟键盘时向上滚动

javascript - 从父级清除输入的 VUE 组件数据

javascript - react : Make flash message disappear automatically

javascript - 将函数参数重新声明为变量?