javascript - 具有多个嵌套子项的单击事件传播
问题描述
在下面的代码中,当我点击任何元素时,每次点击我只会看到一个事件被触发(登录到控制台)。从我读过的内容来看,我认为我应该看到由于事件传播和冒泡而发生鼠标单击的每个元素的控制台日志。不过,似乎我只得到了嵌套最深的元素的事件。
例如,当单击按钮时,我如何确定所单击按钮的 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>
解决方案
推荐阅读
- sql - 为另一个表中的每一行插入多行
- json - 将json字符串转换为数组
- java - 在 Heroku 上部署 .war 文件后的 HTTP 404 状态
- flutter - 无法在运行 Flutter 应用程序时使用 BuildSessionScopeServices 创建 ScriptPluginFactory 和 FileHasher 类型的服务?
- vue.js - Vue-Bootstrap:增加输入字段宽度+响应性
- c# - 为 IncludeAssets 创建具有特定默认值的 nuget 包
- javascript - 如何在javascript中获取所有地图值的总和?
- sql - 动态连接表中的所有列
- sql - 统计 select 语句中的所有行,结果值包含 select 中的所有行号
- java - 空手道框架 - 模拟服务器定义线程池