javascript - 检测用户是否点击了 6 个 div id 元素中的任何一个
问题描述
我有 6 个 div id,我需要写一个条件,只有当用户点击了这6 个唯一 id 中if
的任何一个时才做某事。
我知道我可以做类似下面的事情,但我真的不想要一个接一个的这些功能中的 6 个。有更好的方法吗?
var el = document.getElementById('one');
el.onclick = function() {
console.log('Click just happened');
};
解决方案
这可能有效。
const father = document.querySelector("#father")
const children = father.children;
[...children].forEach(button => {
button.addEventListener("click", (e) => {
console.log(e.target.innerText)
})
})
<div id="father">
<button>one</button>
<button>two</button>
<button>three</button>
<button>four</button>
</div>
推荐阅读
- javascript - 如何在 python 中添加 folium 的 BoatMarker 和其他图层?
- nginx - amzn2 和 nginx 流配置
- python - 如何检测 zstd 压缩?
- python - '找不到模块错误' -pbixrefresher 实用程序
- entity-framework - 为什么我的 EF6 生成的关系不起作用?
- svg - Svg,用边界半径绘制部分圆
- visual-studio-code - Vscode 扩展:在某个位置插入一些元文本?
- batch-file - bat 文件 - 如果特定行包含“错误”,则为特定行着色
- reactjs - 带有禁用日期的 ReactJS 日期范围选择器 - Rsuite
- r - 带有 Apache WebSocket 的 Shiny-Server 失败