1

I know I can use the let keyword here to get the desired outcome, but I would like to know why clicking on the div items alerts #5 for each div.

var div;
var box = document.getElementById('box');
for (var i = 0; i < 5; i++) {
  div = document.createElement('div');
  div.onClick = function() {
    alert('this is box # ' + i);
  }
  box.appendChild(div);
}
<div id="box"></div>
j08691
  • 204,283
  • 31
  • 260
  • 272
Ana kamilova
  • 11
  • 1
  • 3

1 Answers1

0

When you assign the anonymous function to the click, it does not run its body. Its body of codes runs only when it is clicked so the first time i variable is used in the function it has already the value of 4. You need to evaluate current value of i while it is in the loop and place it in the function generated, by a function generating function. Otherwise it will take a reference to i and use its latest value always.

huseyin tugrul buyukisik
  • 11,469
  • 4
  • 45
  • 97