首页 > 解决方案 > 检测用户是否点击了 6 个 div id 元素中的任何一个

问题描述

我有 6 个 div id,我需要写一个条件,只有当用户点击了这6 个唯一 id 中if的任何一个时才做某事。

我知道我可以做类似下面的事情,但我真的不想要一个接一个的这些功能中的 6 个。有更好的方法吗?

var el = document.getElementById('one');

el.onclick = function() {
    console.log('Click just happened');
};

标签: javascriptecmascript-6

解决方案


这可能有效。

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>


推荐阅读