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