Vanilla JS:捕获包装元素点击,但从不捕获其子元素

Vanilla JS: Capture wrapping element click, but never its children

我有一个 div (A),其中包含另一个 div (B)。

当我点击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])
  });

});