提问人: 提问时间:11/23/2020 最后编辑:Liam 更新时间:12/17/2020 访问量:1192
如何获取被单击的元素的最高父元素,该元素仍然是添加事件侦听器的元素的子元素?
How to get the highest parent element of an element that was clicked on that is still a child of the element that the event listener was added to?
答:
0赞
Teemu
11/23/2020
#1
我认为你必须采用“老式”的方式,即遍历父母,直到找到正确的孩子。event.target
const target = document.getElementById('currentTarget');
target.addEventListener('click', function(e) {
let target = e.target,
parent = target,
outmost = e.currentTarget;
console.log('The clicked element is', target.id);
while (parent) {
if (parent.parentElement === outmost) {
break;
}
parent = parent.parentElement;
}
console.log(parent ? 'Hit ' + parent.id : 'didn\'t hit');
});
div {
margin: 20px;
border: 3px solid #ccc;
}
<div id="currentTarget">
<div id="wantedElement">
<div id="intermediate1">
<div id="intermediate2">
<div id="mostInner"></div>
</div>
</div>
</div>
</div>
此算法是通用的,它可以与任何 HTML 结构一起使用,并且结果不依赖于元素的任何标识符。在外部包装器中查看带有两个子项的 jsFiddle。
评论