0

I just to want to see: click link0, alert 0, click linkn, alert n. But in my code, whichever link I click, the alert is n.

SO in this case, I can see link0 link1 ... link4, but whichever link I click , it alerts 5.

Body is empty

Javascript code is as follows:

 for(var i = 0; i < 5; i++) {

    var link =   document.createElement("a");


    link.innerHTML = "Link " + i;

    link.onclick =function(){alert(i)};

    document.body.appendChild(link);
}
Allen Liu
  • 29
  • 1
  • 7
  • https://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example same quesiton from here – Allen Liu Oct 28 '19 at 20:35
  • the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function. – Allen Liu Oct 28 '19 at 20:43

1 Answers1

0

You need to wrap the inside of the loop in a closure.

for (var i = 0; i < 5; i++) {
  (function(index) {
    var link = document.createElement("a");
    link.innerHTML = "Link " + index;
    link.onclick = function() {
      alert(index)
    };
    document.body.appendChild(link);
  })(i);
}
a { display: block; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132
  • Thanks, I found the from the same question, someone mentioned that using let instead of var would solve the problem quickly – Allen Liu Oct 28 '19 at 20:29