JavaScript To Add Table Row Onclick Events
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
Solution 1:
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.
Solution 2:
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. I.e:
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.
Solution 3:
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>
Post a Comment for "JavaScript To Add Table Row Onclick Events"