0

I have logic in which I need to dynamically build HTML elements where the parameters of the function given to an event element are dependent on the iteration variable.

The example below does not include parameters but it does produce the same behavior I wish to correct.

Here, the value of i will be shadowed by each iteration resulting in a value of '10' being alerted for each button that is clicked.

I'd like to not only correct this behavior (so that each button alerts the value corresponding to the iteration in which it was created) without drastically changing my approach but also gain a better understanding of why this behavior is occurring.

for (var i = 1; i<10; i++) {

    var newButton = document.createElement("button");

    newButton.innerHTML = "Button" + i;
    newButton.onclick = function() { alert(i) };

    document.getElementById('container').appendChild(newButton);
}

jsfiddle: https://jsfiddle.net/poggtfnx/3/

  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Jeremy J Starcher Jun 18 '16 at 05:07
  • I voted to close your question because this is a VERY common question in JavaScript that has some very, very good answers out there already. It is something that is very hard to search for if you don't already know the answer to, though. – Jeremy J Starcher Jun 18 '16 at 05:09

1 Answers1

0

This behavior happens because the i variable used is the reference to the same variable. It means that is not the value that is kept for the onclick function, but its reference. So, the last value will always be used.

One way to fix it is to keep your value into the DOM element itself.

newButton["data-i"] = i;

Here's my fiddle : https://jsfiddle.net/poggtfnx/5/

Master DJon
  • 1,899
  • 2
  • 19
  • 30