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?
Code above should work. In your case it does not works because you have a closure to
idefined infor (var i = 0Basically,iwhich you pass todeleteRowspoints toidefined inforwhich at that moment will be equal totbl.rows.lengthMy code creates new closure for each cycle of loop. For more information google javascript closure.