I was messing around with some javascript, on jsfiddle, and ran into a strange issue. I can't seem to figure out why I am unable to set onclick
event handlers via a for loop:
html:
<table border="1" cellspacing="1" width="500">
<tr id="headerRow">
<td>Header1</td>
<td>Header2</td>
<td>Header3</td>
<td>Header4</td>
</tr>
<tr>
<td>books</td>
<td>red</td>
<td>peas</td>
<td>321</td>
</tr>
<tr>
<td>tapes</td>
<td>blue</td>
<td>jello</td>
<td>654</td>
</tr>
</table>
js executed in DOM ready:
var arr = document.getElementById('headerRow')
.getElementsByTagName("td");
// Why does this work??
/*arr[0].onclick = function() { alert(arr[0].innerHTML); };
arr[1].onclick = function() { alert(arr[1].innerHTML); };
arr[2].onclick = function() { alert(arr[2].innerHTML); };
arr[3].onclick = function() { alert(arr[3].innerHTML); };
*/
//But this doesn't????
for(var i = 0; i < arr.length; i++) {
arr[i].onclick = function() { alert(arr[i].innerHTML); };
}