如何将事件侦听器添加到一行中的多个元素
问题描述:
示例1
Element1.addEventListener ("input", function() {
this function does stuff
});
示例2
Element1 && Element2.addEventListener("input", function() {
this function does stuff
});
语法上可能不正确,但是有没有办法我可以在同一时间(同一行)为两个元素提供相同的Dom方法,而不必将它们分开书写?
it might not be correct grammatically, but is there a way i can give two elements the same Dom method at the same time (same line) instead of having to write them apart?
答
好吧,如果您有一个包含元素的数组,则可以这样做:
Well, if you have an array with the elements you could do:
let elementsArray = document.querySelectorAll("whatever");
elementsArray.forEach(function(elem) {
elem.addEventListener("input", function() {
//this function does stuff
});
});