首页 > 解决方案 > 具有多个嵌套子项的单击事件传播

问题描述

在下面的代码中,当我点击任何元素时,每次点击我只会看到一个事件被触发(登录到控制台)。从我读过的内容来看,我认为我应该看到由于事件传播和冒泡而发生鼠标单击的每个元素的控制台日志。不过,似乎我只得到了嵌套最深的元素的事件。

例如,当单击按钮时,我如何确定所单击按钮的 ID 是什么,因为事件目标始终是子图像。我是否只需要知道 HTML 结构并询问 e.target.parentNode 还是有更优雅的方式来访问事件传播树中的中间节点?

document.getElementById('parent')
.addEventListener('click', function(e) {
  console.log(e.target.nodeName + ' ' + e.target.id);
});
#parent {
  border: thin black solid;
  width: 200px;
  height: 200px;
}

#child1, #child2 {
  border: thin green solid;
  width: 100px;
  height: 100px;
}

#btn1, #btn2 {
  border: thin red solid;
  width: 50px;
  height: 50px;
}

#image1, #image2 {
  width: 100%;  
  height: 100%;
}
<div id="parent">
  <div id="child1">
    <button id="btn1">
      <img id="image1" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
    </button>
  </div>
  <div id="child2">
    <button id="btn2">
      <img id="image2" src="https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png">
    </button>
  </div>  
</div>

标签: javascripthtmlevent-propagation

解决方案


推荐阅读