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>
This seem to be the canonical way
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.
I'm not quite sure why you're using a closure here, could you be a bit more elaborate?
The reason you're not seeing the desired alert is because within the onclick function, you're returning another function. Ie:
window.onload = function() {
return function() {
alert("Closure... why?");
};
};
Something like this won't really work because you're never calling the nested function... try it without using the closure, or comment explaining why you want a closure because you're explanation didn't make much sense to me.
You just have to remove an extra function and script will be like this
<script>
function example4() {
var table = document.getElementById("tableid4");
cells = table.getElementsByTagName('td');
for (var i=0,len=cells.length; i<len; i++){
cells[i].onclick = function(){
alert(this.innerHTML);
}
}
}
function init() { example4(); }
window.onload = init;
</script>
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.