John Resig 在“JavaScript Ninja 的秘密”(http://ejohn.org/apps/learn/#59 http://ejohn.org/apps/learn/#59 )
您需要创建一个临时范围来保留 i 的值
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
这应该可以满足您的要求,因为我正在工作,所以现在无法测试它。