[英]List of generated event listeners only triggers last one
Here is the full code for demonstration: http://jsfiddle.net/DF2Uw/4/ 这是演示的完整代码: http : //jsfiddle.net/DF2Uw/4/
Basically, I generate multiple event listeners with a FOR
loop. 基本上,我使用
FOR
循环生成多个事件侦听器。 I generate multiple <selects>
and want to detect the onChange event and return the ID of the specific select that was changed. 我生成了多个
<selects>
并且想要检测onChange事件并返回已更改的特定选择的ID。 However it seems only the last eventlistener survives as the others do no trigger. 但是,似乎只有最后一个事件侦听器得以幸存,而其他事件侦听器没有触发。
Any explanation for this behavior? 对这种行为有任何解释吗?
HTML HTML
<ol id="slots"></ol>
JAVASCRIPT JAVASCRIPT
var slotnameHtml = '';
for (var i = 0; i < 3; i += 1) {
var slotname = document.createElement('select'),
slottime = document.createElement('select'),
slotlist = document.createElement('li');
slotname.innerHTML = slotnameHtml;
slottime.innerHTML = '<optgroup><option value="1">00:01</option><option value="2">00:02</option></optgroup>';
slottime.id='test'+i;
slotlist.appendChild(slotname);
slotlist.appendChild(slottime);
document.getElementById('slots').appendChild(slotlist);
slottime.addEventListener('change', function () {
alert(slottime.id)
});;
}
That's because the handlers you bind to change
do not run immediately, but later. 这是因为绑定到
change
的处理程序不会立即运行,而是稍后运行。 In the meantime, your for
loop has run its course and slottime
has been rebound to its final value (the last <select>
element you created). 同时,您的
for
循环已完成,并且slottime
已反弹至其最终值(您创建的最后一个<select>
元素)。 All the handlers will only see that value. 所有处理程序将仅看到该值。
You can introduce a closure in order for the right elements to be accessible to the handlers: 您可以引入闭包以使处理程序可以访问正确的元素:
document.getElementById("slots").appendChild(slotlist);
(function(slottime) {
slottime.addEventListener("change", function() {
alert(slottime.id);
});
})(slottime);
As Teemu righfully says in the comments, the simplest solution is to take advantage of the fact that this
is bound to the target element inside the handler: 正如Teemu在评论中严格地说的那样,最简单的解决方案是利用以下事实:
this
绑定到处理程序内的目标元素:
slottime.addEventListener("change", function() {
alert(this.id);
});
您必须使用以下insted警报参数:
alert(this.getAttribute('id'));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.