我有一个包含另一个div(B)的div(A)。
[当我单击A时,我希望e.target
为A。当我单击B时,我也希望e.target
为A。
由于必须单击包装元素才能获取内部元素,因此如何告诉JS永远不要B?
我知道它与冒泡有关,但是我已经尽力而为,似乎无济于事。
// none of these work
e.preventDefault()
e.stopPropagation()
e.stopImmediatePropagation()
e.cancelBubble = true
// adding { capture: false } doesn't help either
这里是一个JSBin简化问题的测试案例。 https://jsbin.com/wezoyoyito/1/edit?html,css,js,console,output
改用event.currentTarget
,它总是引用侦听器所附加的元素(而不是内部单击的元素):
document.querySelectorAll('.a').forEach(el => {
el.addEventListener('click', e => {
console.log(e.currentTarget.className)
})
})
.a {
background: red;
width: 100px;
height: 100px;
}
.b {
background: yellow;
width: 80px;
height: 80px;
}
<div class="a">
A
<div class="b">B</div>
</div>
我尝试测试以下代码,应该能够根据您的需求工作。
document.querySelectorAll('.a').forEach(el => {
el.addEventListener('click', e => {
e.preventDefault();
let target = e.target;
while (target !== el) {
target = target.parentNode;
}
console.log(Array.from(target.classList)[0])
});
});