I\'m new to Javascript. I want to add onclick events to table rows. I\'m not using JQuery.
I loop thru the rows and use a closure to make sure I have the state of th
This seem to be the canonical way
DEMO
function example4() {
var table = document.getElementById("tableid4");
var rows = table.rows; // or table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
rows[i].onclick = (function() { // closure
var cnt = i; // save the counter to use in the function
return function() {
alert("row"+cnt+" data="+this.cells[0].innerHTML);
}
})(i);
}
}
window.onload = function() { example4(); }
UPDATE: @ParkerSuperstar suggested that the i in (i) is not needed. I have not tested this but his fiddle seems to work.