Possible Duplicate:
Assign click handlers in for loop
I need help with a loop in my code.
I loop through an array and add on clicks to divs. But it always adds onclicks to the last cycle through the loop and effectively cancels out the ones before it.
So i have this as my loop:
start = 0;
for(i = start; i < (start+8); i++){ //8 per page
if(i == array.length){
break; //page end
} else {
(function(i){
document.getElementById('cell'+i).onclick = function(){ select(i); }
})(i);
}
}
What occurs here is div id cell7 gets the on click added, but the div ids cell0 to cell6 do not. I’m guessing its something to do with the fact that i changes in the loop and so is also effected the i in the function ?
How do I fix this problem ?
I’m not sure why but these suggestions didn’t fix my problem – but i managed to find a way around it by adding to the onclicks as i display the divs during the loop so i ended up doing:
Instead of adding the divs to the output “then” assigning the onclicks later… don’t know if my new method is the best choice but it works so i’ll have to stick to it!