You can add an event listener to all the elements returned by a document.querySelectorAll()
call by iterating over those results using the for..of
loop:
您可以使用for..of
循环遍历那些结果,从而将事件侦听器添加到document.querySelectorAll()
调用返回的所有元素中:
const buttons = document.querySelectorAll("#select .button")
for (const button of buttons) {
button.addEventListener('click', function(event) {
//...
})
}
It’s important to note that document.querySelectorAll()
does not return an array, but a NodeList object.
重要的是要注意document.querySelectorAll()
不会返回数组,而是一个NodeList对象。
You can iterate it with forEach
or for..of
, or you can transform it to an array with Array.from()
if you want.
您可以使用forEach
或for..of
进行迭代,也可以根据需要使用Array.from()
将其转换为数组。