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?

0

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.