3

every click get out 4 not expected button : is it about scope ?

<button id="button-1">one</button>
<button id="button-2">two</button>
<button id="button-3">three</button>
<p>Then you assign click event handlers in a loop: </p>
<script>
    for (var i = 1; i <= 3; i++) {
        // alert(i);
        document.getElementById('button-' + i).onclick = function(){
            alert("This is button: " + i);
        };
    }
</script>
Dev_meno
  • 124
  • 14

1 Answers1

1

You have to fix it by using let,

for (let i = 1; i <= 3; i++) {
  document.getElementById('button-' + i).onclick = function(){
   alert("This is button: " + i);
  };
}

Or create a scope per iteration,

for (var i = 1; i <= 3; i++) {
 (function(i) {
   document.getElementById('button-' + i).onclick = function(){
    alert("This is button: " + i);
   };
 })(i);
}
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130