gpt4 book ai didi

javascript - 更改事件目标

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

我有以下 html:

<div id="div1">
<div id="div2">
</div>
</div>

JS:

document.addEventListener('mousedown', function(e){
console.log(e.target);
});

如果鼠标在 div2 上单击,则 e.target 为 div2。在这种情况下,我希望目标为 div1。可能吗?

最佳答案

最简单的方法可能是向上遍历 DOM 树,直到找到您想要的元素。

document.addEventListener('mousedown', function(e) {

// start with the element that was clicked.
var parent = e.target;

// loop while a parent exists, and it's not yet what we are looking for.
while (parent && parent.id !== 'div1') {

// We didn't find anything yet, so snag the next parent.
parent = parent.parentElement;
}

// When the loop exits, we either found the element we want,
// or we ran out of parents.
console.log(parent);
});​

示例:http://jsfiddle.net/7kYJn/

关于javascript - 更改事件目标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14106905/

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