gpt4 book ai didi

javascript - 如何在 JavaScript 中找到其父项的子位置

转载 作者:行者123 更新时间:2023-11-30 11:08:55 24 4
gpt4 key购买 nike

当我点击一个元素时,我想通过它的父元素(使用 JavaScript)找出它的子元素位置。

谁能帮我解决这个问题?谢谢。

最佳答案

使用.parentNode获取父级的句柄,然后使用 Array.indexOf在它的 .children 中找到元素的索引数组。

function findPos(el) {
const i = Array.from(el.parentNode.children).indexOf(el)

console.log(i)
}
<div>
<button onclick="findPos(this)">Click Me</button>
<button onclick="findPos(this)">Click Me</button>
<button onclick="findPos(this)">Click Me</button>
<button onclick="findPos(this)">Click Me</button>
<button onclick="findPos(this)">Click Me</button>
</div>

关于javascript - 如何在 JavaScript 中找到其父项的子位置,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54537869/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com