繁体   English   中英

单击时返回子节点的索引

[英]return the index of childnode when clicked

在这里,我的父 div 为 class =“alphabets”,子 div 的全部相同 class =“word”

<div class="alphabets">
  <div class="word"> abc </div> //1st child
  <div class="word"> def </div> //2nd child
  <div class="word"> ghi </div> //3rd child
  <div class="word"> jkl </div> //4th child
  <div class="word"> mno </div> //5th child
</div>

我需要的是当我点击“jkl”时。 fun() 应该返回它的索引,即它是第一个孩子还是第二个孩子或第六个孩子......

您可以在父元素的children元素(将其转换为数组后)上使用indexOf

 document.querySelector('.alphabets').addEventListener('click', function(e){ if (e.target.matches('.word')) console.log([...this.children].indexOf(e.target)); });
 <div class="alphabets"> <div class="word"> abc (1st child)</div> <div class="word"> def (2nd child)</div> <div class="word"> ghi (3rd child)</div> <div class="word"> jkl (4th child)</div> <div class="word"> mno (5th child)</div> </div>

问题未解决?试试以下方法:

单击时返回子节点的索引

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2023 STACKOOM.COM