0

Possible Duplicate:
Event handlers inside a Javascript loop - need a closure?

I am having hrefs in table cells.
I am iterating through those cells with a 'for' loop to change the onclick function.
But this does not work.
Here are 2 examples:

This works:

for (var i = 0; i < tbl.rows.length - 1; i++) { // for each row
    var len = document.getElementById("my_table").rows[i].cells.length-1;
    document.getElementById("my_table").rows[i].cells[len].innerHTML = "X1";
  }

This does not work:

for (var i = 0; i < tbl.rows.length; i++) { // for each row
    var len = document.getElementById("my_table").rows[i].cells.length-1;
    document.getElementById("my_table").rows[i].cells[len].onclick = function() {
        deleteRows(i);
    };
  }

What could be wrong?

Community
  • 1
  • 1
HoGo
  • 933
  • 4
  • 11
  • 17

1 Answers1

8
for (var i = 0; i < tbl.rows.length; i++) { // for each row
    var len = document.getElementById("my_table").rows[i].cells.length-1;
    document.getElementById("my_table").rows[i].cells[len].onclick = (function(index) { return function() {
        deleteRows(index);
    };})(i);
  }

Code above should work. In your case it does not works because you have a closure to i defined in for (var i = 0 Basically, i which you pass to deleteRows points to i defined in for which at that moment will be equal to tbl.rows.length My code creates new closure for each cycle of loop. For more information google javascript closure.

Viktor S.
  • 12,736
  • 1
  • 27
  • 52