I am looking into some common Javascript programs. The following one adds 4 buttons to the DOM and adds an event listener to each of them:
for(var i =0;i<5;i++){
var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button' + i));
//function 1
(function(i){
btn.addEventListener('click', function(){console.log(i)});
})(i);
//function 2 commented
/*btn.addEventListener('click', (function(i){
return function(){
console.log(i);
}
})(i));*/
document.body.appendChild(btn);
}
both function 1 and function 2 add event listener to the buttons and work perfectly. I want to know, why the following code does not :-
for(var i =0;i<5;i++){
var btn = document.createElement('button');
btn.appendChild(document.createTextNode('Button' + i));
btn.addEventListener('click', function(){
console.log('Clicked' + i);
});
document.body.appendChild(btn);
}
This code just logs 5 for every button on click. Why is that, I do not understand why it simply does not hold the value for i for each loop?