我有 6 个 div id,我需要编写一个 if
条件,仅当这些 6 个唯一 id 中的任何一个被点击时才执行某些操作用户。
我知道我可以做如下的事情,但我真的不想要一个接一个的 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 - 检测用户是否点击了 6 个 div id 元素中的任何一个,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60366401/