如何将EventListener添加到一行中的多个元素 [英] How to addEventListener to multiple elements in a single line

查看:24
本文介绍了如何将EventListener添加到一行中的多个元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

示例 1:

element1.addEventListener("input", function() {
this function does stuff 
});

示例 2:

element1 && element2.addEventListener("input", function() {
this function does stuff
});

这在语法上可能不正确,但是有没有一种方法可以同时(同一行)为两个元素提供相同的事件侦听器,而不必将它们分开?

It might not be correct grammatically, but is there a way I can give two elements the same event listener 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
    });
});

这篇关于如何将EventListener添加到一行中的多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆