问题
Here is the full code for demonstration: http://jsfiddle.net/DF2Uw/4/
Basically, I generate multiple event listeners with a FOR
loop. I generate multiple <selects>
and want to detect the onChange event and return the ID of the specific select that was changed. However it seems only the last eventlistener survives as the others do no trigger.
Any explanation for this behavior?
HTML
<ol id="slots"></ol>
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)
});;
}
回答1:
That's because the handlers you bind to change
do not run immediately, but later. 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). 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:
slottime.addEventListener("change", function() {
alert(this.id);
});
回答2:
You have to use the following alert parameter insted:
alert(this.getAttribute('id'));
来源:https://stackoverflow.com/questions/22966135/list-of-generated-event-listeners-only-triggers-last-one