Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
45
rated 0 times [  46] [ 1]  / answers: 1 / hits: 48000  / 11 Years ago, sun, april 7, 2013, 12:00:00

I've tried to create a loop with for, and increment by an onclick event, but it doesn't work.


var gameCase = ['', '', '', '', '', '', '', '', ''],  // 9
itemLists = $('game').getElementsByTagName('li'); // 9 items

for( var i = 0; i < itemLists.length; i++ ) {
// i already equals 9
itemLists[i].onclick = function() {
// do something
}
}

But in this case, the for loop is finished before I was able to click on an element in the list.


Moreover, I would like to get the item list I clicked and save it in an array. I tried gameCase[this] (in onclick function), but I don't know if it's the good way.


More From » for-loop

 Answers
9

John Resig covers this topic very well in Secrets of the JavaScript Ninja ( http://ejohn.org/apps/learn/#59 )



You'll need to create a temporary scope to preserve i's value



for ( var i = 0; i < itemLists.length; i++ ) (function(i){ 
itemLists[i].onclick = function() {
// do something
}
})(i);


Edit:



var gameCase = ['', '', '', '', '', '', '', '', ''], // 9
$listParent = $('game').find('ul'), // li's parent
itemLists = $('game').getElementsByTagName('li'); // 9 items

var listHandler = (function() {
var i = 0;

return function() {
// $(this) will in here refer to the clicked li
i++ // increment i

if ( i === 9 ) {
$listParent.off('click', 'li', listHandler); //remove eventhandler when i reaches 9
}
}
}());

$listParent.on('click', 'li', listHandler); // attach eventhandler to ul element


This should do what you want, cant test it right now since I'm at work.


[#79075] Friday, April 5, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
cullenmaxl

Total Points: 414
Total Questions: 112
Total Answers: 87

Location: United States Minor Outlying Island
Member since Sat, May 28, 2022
2 Years ago
;