jbr*_*jbr 13 javascript for-loop
我试图创建一个带有for的循环,并通过onclick事件递增,但它不起作用.
js的一部分:
var gameCase = ['', '', '', '', '', '', '', '', ''], // 9
itemLists = $('game').getElementsByTagName('li'); // 9 items
for( var i = 0; i < itemLists.length; i++ ) {
// i already egal to 9
itemLists[i].onclick = function() {
// do something
}
}
Run Code Online (Sandbox Code Playgroud)
但在这种情况下,在我能够单击列表的元素之前,For循环已经完成.
此外,我想获取我点击的项目列表并将其保存在阵列上.我尝试了一个gameCase [this](在onclick函数中),但我不知道它是否是好方法.
ruu*_*ska 23
John Resig在"JavaScript忍者的秘密"中非常清楚地介绍了这个主题(http://ejohn.org/apps/learn/#59)
您需要创建一个临时范围来保留i的值
for ( var i = 0; i < itemLists.length; i++ ) (function(i){
itemLists[i].onclick = function() {
// do something
}
})(i);
Run Code Online (Sandbox Code Playgroud)
编辑:
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
Run Code Online (Sandbox Code Playgroud)
这应该做你想要的,因为我在工作,现在不能测试它.
包裹你的听众:
onclick = (function(i) {return function() {
...
};})(i);
Run Code Online (Sandbox Code Playgroud)
这可以修复您的可变范围问题.