JSFiddle - React, Tailwind, and code Playground
by kalar su
HTML
<button id="btn1">click</button>
<button id="btn2">click</button>
JavaScript
//To resolve using closure in a loop, the closure must be decoupled from the actual loop variable. This can be done by calling a new function, which in turn creates a new referencing environment.
for(var i=1; i<=2; i++){
var btn = document.getElementById("btn"+i);
btn.addEventListener("click", getHandler(i));
}
function getHandler(i){
return function handler(){
switch(i){
case 1:
alert("show first message for buton:"+i);
break;
case 2:
alert("show second message for buton:"+i);
break;
}
}
}