如何将事件侦听器添加到一行中的多个元素 [英] How to addeventlistener to multiple elements in a single line
本文介绍了如何将事件侦听器添加到一行中的多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例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
});
});
这篇关于如何将事件侦听器添加到一行中的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文