我想在点击每个子节点时显示它的索引(编号)



这里我有一个包含几个子节点的父节点。我想通过单击控制台上的每个子节点来显示它的索引(编号)。我试图使用forEach方法来检测点击的孩子,但当我试图得到我点击它不工作的孩子的索引。我尝试indexOf()方法,但它显示一个错误

let parent = document.querySelector('.parent');
let children = document.querySelectorAll('.child');
children.forEach(child => {
child.onclick = function () {
console.log( /* children.indexOf(child) */ ) 
// this is the method i tried but it didn't worked

console.log( /*here i want to display the index of the clicked child */ );
}
});
<div class="parent">
<div class="child">a</div>
<div class="child">b</div>
<div class="child">c</div>
<div class="child">d</div>
</div>

您只需要将children从NodeList转换为数组(使用Array.from)即可使用indexOf:

let parent = document.querySelector('.parent');
let children = document.querySelectorAll('.child');
children.forEach(child => {
child.onclick = function () {
console.log(Array.from(children).indexOf(child));
}
});
<div class="parent">
<div class="child">a</div>
<div class="child">b</div>
<div class="child">c</div>
<div class="child">d</div>
</div>

最新更新