1

Basically I created a bunch of cells and I am trying to add onclick to each one passing a variable to use inside the function. But doing straight up passes the 'i' variable as the last i value and not 0,1,2,3,4 etc. Here is a snippet of what I am doing.

for (var i = 0; i < cellCount.length; i++) {

        var cellName= "cell"+ i

document.getElementById(cellName).onclick = function () { cellClicked(i) };

}
F U
  • 91
  • 1
  • 8

1 Answers1

1

If you do not "capture" the value in a new scope, the callback will read the value from the actual i-counter.

Do something like this:

for (var i = 0; i < cellCount.length; i++) {

    (function(copy_of_i) {
        var cellName= "cell"+ i
        document.getElementById(cellName).onclick = function () { cellClicked(copy_of_i)     };
    })(i)
}
folkol
  • 4,752
  • 22
  • 25