Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
83
rated 0 times [  84] [ 1]  / answers: 1 / hits: 26102  / 12 Years ago, wed, december 26, 2012, 12:00:00

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 the outer function for each row.
The looping works. Using alerts, I see the function being assigned for each iteration. But when I click the row, no alert is displayed.
Below is the HTML and code that can be loaded.



Why are the table row events not working?



<!doctype html>
<html lang=en>
<body>
<script>
function example4() {
var table = document.getElementById(tableid4);
var rows = table.getElementsByTagName(tr);
for (var i = 0; i < rows.length; i++) {
var curRow = table.rows[i];
//get cell data from first col of row
var cell = curRow.getElementsByTagName(td)[0];
curRow.onclick = function() {
return function() {
alert(row + i + data=+ cell.innerHTML);
};
};
}
}
function init() { example4(); }
window.onload = init;
</script>
<div>
Use loop to assign onclick handler for each table row in DOM. Uses Closure.
<table id=tableid4 border=1>
<tbody>
<tr><td>Item one</td></tr>
<tr><td>Item two</td></tr>
<tr><td>Item three</td></tr>
</tbody>
</table>
</div>
</body>
</html>

More From » javascript

 Answers
17

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.


[#81222] Monday, December 24, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
gabriel

Total Points: 323
Total Questions: 107
Total Answers: 108

Location: Federated States of Micronesia
Member since Sun, May 16, 2021
3 Years ago
;