hello
I’m new to Javascript and I have just got myself into a dead end. My problem is that when I attach a function to an onclick handler of an element I cannot seem to be able to feed it with a variable. It will only get the last value, when the loop has ended. Here is the code. The first lines are initialization and HTML element generation, my problem is very simple to understand and lies in the last lines of this code. All the ’tile’ elements will have a onclick=printMe(9) event, but i want it to be printMe(1), printMe(2)…printMe(9) for my 9 tiles.
window.onload=init;
function init() {
new Board();
}
function Board() {
DOMboard=document.getElementById(‘board’);
for(i=0; i<9; i++) {
tile = document.createElement(‘a’);
tile.setAttribute(‘href’, ‘#’);
tile.appendChild(document.createTextNode(i));
DOMboard.appendChild(tile);
//problem here, no matter which ’tile’ i click
//it will always print 9 which is the last
//value of i after the loop has ended.
tile.onclick=function(){printMe(i)};
}
function printMe(z) {
alert(z);
}
}
Regards