Javascript 为多个元素添加事件监听器
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13915702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding event listeners to multiple elements
提问by Christian Lundahl
I've been struggling with this for a good couple of hours now.
我已经为此苦苦挣扎了好几个小时了。
I want to add an event listener to all <select>s on a page and I've got this piece of code so far:
我想为<select>页面上的所有s添加一个事件侦听器,到目前为止我已经得到了这段代码:
onload = function(e) {
sels = document.getElementsByTagName('select');
for(i=0; i<sels.length; i++) {
sels[i].addEventListener('change', alert('test!'), false);
}
}
This only triggers the alert when the page is loaded and not when I change the value in any of my <select>s.
这仅在页面加载时触发警报,而不是在我更改任何<select>s 中的值时触发。
Can I get a nudge in the right direction, please? :-)
请问我可以朝正确的方向推动吗?:-)
采纳答案by antyrat
You need to have there anonymous function for that as you invoke alert()function immediately in your example:
当您alert()在示例中立即调用函数时,您需要有匿名函数:
... .addEventListener('change', function() { alert('test!')}, false ...
For now according to your code addEventListenertries to add result of undefined(return of alert()function).
现在根据您的代码addEventListener尝试添加undefined(alert()函数返回)的结果。
Or you can just pass function handler for that:
或者您可以为此传递函数处理程序:
function alertMe() {
alert( 'test!' );
}
...
... .addEventListener('change', alertMe, false ...
Note: that by making somefunction(arg[, arg...])call you reference not to function, but to what function returns.
注意:通过somefunction(arg[, arg...])调用,您引用的不是函数,而是函数返回的内容。
回答by Cerbrus
Aside from wrapping the alertin a function, like mentioned before, don't use getElementsByTagNamefor every iteration of the loop:
除了将 包装alert在一个函数中,就像前面提到的,不要getElementsByTagName在循环的每次迭代中使用:
onload = function(e) {
sels = document.getElementsByTagName('select');
for(i=0; i<sels.length; i++) {
sels[i].addEventListener('change', function(){alert('test!')}, false);
}
}
You have the list of selectelements saved to a variable, it's not necessary, not to mention inefficient to getall these elements, each loop iteration.
您将select元素列表保存到变量中,这是没有必要的,更不用说get每次循环迭代对所有这些元素都效率低下。
回答by isapir
I created the following simple function, which iterates over all of the elements that match the selector, and add an event listener for the eventwith the passed handler.
我创建了以下简单函数,该函数遍历所有与 匹配的元素selector,并为event传递的handler.
This is similar functionality for jQuery's $(selector).on(event, handler)
这是 jQuery 的类似功能 $(selector).on(event, handler)
function addEventListeners(selector, event, handler, useCapture){
useCapture = useCapture || false;
Array.prototype.forEach.call(
document.querySelectorAll(selector)
,function(el, ix) {
el.addEventListener(event, handler, useCapture);
}
);
}
So for the OP the way to use this function would be like so:
所以对于 OP 来说,使用这个函数的方法是这样的:
addEventListeners("select", "change", function(evt){ console.log(evt); });
See also my answer for Event listener for current and future elements
另请参阅我对当前和未来元素的事件侦听器的回答
回答by Ayush Sharma
Event Bubbling is the important concept in javascript, so if you can add event on DOM directly, you can save some lines of code :
事件冒泡是javascript中的一个重要概念,所以如果你可以直接在DOM上添加事件,你可以节省一些代码:
document.addEventListener('change', function(e){
if(e.target.tagName=="SELECT"){
alert('SELECT CHANGED');
}
})
回答by Will C.
You are executing the alert() function immediately, you need to pass the addEventListener function a function instead, so:
您正在立即执行 alert() 函数,您需要向 addEventListener 函数传递一个函数,因此:
onload = function(e) {
sels = document.getElementsByTagName('select');
for(i=0; i<sels.length; i++) {
document.getElementsByTagName('select')[i].addEventListener('change', function () { alert('test!'); }, false);
}
}

