JSFiddle - React, Tailwind, and code Playground
by kalar su
HTML
<button id="btn1">click</button>
<button id="btn2">click</button>
JavaScript
//Creating closures within loops can have misleading results. By the time one of the buttons is clicked, the loop has finished executing, and the loop variable has reached its final value of 2.
var nodes = document.getElementsByTagName('button');
for (var i = 0; i < nodes.length; i++) {
nodes[i].addEventListener('click', function() {
console.log('You clicked element #' + i);
});
//following is to fix above problem
/*nodes[i].addEventListener('click', (function(i) {
return function() {
console.log('You clicked element #' + i);
}
})(i));*/
}