I have a question on the following for loop in javascript - the purpose of the for loop is simple, they are meant to listen to the event for all of the columns that i have.
I have two methods to achieve this, i wonder why one works but not another.
First method that DOES NOT work:
var column = document.querySelectorAll("td");
for (var i =0 ; i< column.length; i++)//column.length is 9
{
column[i].addEventListener("click",function(){
column[i].innerText = "X";
})
}
it prints out the following error when the event is triggered:
Uncaught TypeError: Cannot set property 'innerText' of undefined at HTMLTableCellElement. (:6:21)
I replaced "column[i].innerText = "X" with console.log(i), i get 9. But according to my for loop condition, it is supposed to end when i reaches 8 as my column.length is 9, and i use i < column.length, so it should stop at 8.
Question: Why can i get 9 in this for loop ? And why my second approach below can work ?
Second method that DOES work:
var column = document.querySelectorAll("td");
for ( var i = 0 ; i < column.length; i++ )
{
column[i] = clickAction(i);
}
function clickAction(param)
{
column[param].addEventListener("click",function(){
column[param].innerText = "X";
})
}
It works fine if i put the action into a function externally.
Thanks