将事件侦听器添加到多个元素 [英] Adding event listeners to multiple elements
问题描述
我一直在努力解决这个问题好几个小时。
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:
onload = function(e) {
sels = document.getElementsByTagName('select');
for(i=0; i<sels.length; i++) {
sels[i].addEventListener('change', alert('test!'), false);
}
}
这只会在页面加载时触发警报不是当我更改任何< select>
s中的值时。
This only triggers the alert when the page is loaded and not when I change the value in any of my <select>
s.
我可以轻轻一点正确的方向,好吗? : - )
Can I get a nudge in the right direction, please? :-)
推荐答案
当你调用 alert()时,你需要有匿名函数/ code>在你的例子中立即起作用:
You need to have there anonymous function for that as you invoke alert()
function immediately in your example:
... .addEventListener('change', function() { alert('test!')}, false ...
现在根据您的代码 addEventListener
尝试添加 undefined
的结果(返回 alert()
函数)。
For now according to your code addEventListener
tries to add result of undefined
(return of alert()
function).
或者你只需传递函数处理程序:
Or you can just pass function handler for that:
function alertMe() {
alert( 'test!' );
}
...
... .addEventListener('change', alertMe, false ...
注意:通过使某些函数(arg [, arg ...])
调用引用不是函数,而是函数返回。
Note: that by making somefunction(arg[, arg...])
call you reference not to function, but to what function returns.
这篇关于将事件侦听器添加到多个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!