我有一个container
有几个孩子的div divs
。每个孩子divs
都有未知的结构和内容。某处有一些按钮应该只返回被点击的根子节点的当前索引。(不使用唯一 ID)
例子:
<div class="conatainer">
<div class="rootChild">
<button> Get rootChild index </button> // should return 0
</div>
<div class="rootChild">
<div class="someDiv">
<p> Some text here </p>
<button> Get rootChild index </button> // should return 1
</div>
</div>
<div class="rootChild">
<div class="someOtherDiv">
<div class="andAnotherDiv">
<button> Get rootChild index </button> // should return 2
</div>
</div>
</div>
</div>
您可以从子类中创建一个数组,并从按钮查找到子类最近的元素,并用于indexOf()
获取该子类在数组中的索引
const cont = document.querySelector('.conatainer'),
children = Array.from(cont.children);
cont.addEventListener('click', e => {
if (e.target.matches('.rootChild button')) {
const idx = children.indexOf( e.target.closest('.rootChild'))
console.log('Index =', idx)
}
})
<div class="conatainer">
<div class="rootChild">
<button> Get rootChild index </button> // should return 0
</div>
<div class="rootChild">
<div class="someDiv">
<p> Some text here </p>
<button> Get rootChild index </button> // should return 1
</div>
</div>
<div class="rootChild">
<div class="someOtherDiv">
<div class="andAnotherDiv">
<button> Get rootChild index </button> // should return 2
</div>
</div>
</div>
</div>
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句