[英]onClick event in a 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
}
}
但在这种情况下,在我能够单击列表的元素之前,For循环已经完成。
此外,我想获取我点击的项目列表并将其保存在阵列上。 我尝试了一个gameCase [this](在onclick函数中),但我不知道它是否是好方法。
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);
编辑:
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
这应该做你想要的,因为我在工作,现在不能测试它。
包裹你的听众:
onclick = (function(i) {return function() {
...
};})(i);
这可以修复您的可变范围问题。
很抱歉,如果我没有正确理解你的问题,从我理解的代码中,你试图在游戏代码中找到的所有列表元素中添加一个onclick处理程序(也许它应该是一个类/ id)。
当脚本标记/文件加载而没有任何用户交互时,将执行for循环。
如果要分配使用计数器当前值的函数。 使用以下代码:
itemLists[i].onclick = (function() {
return function() {
// TODO ---
// Your handler code here
}
})();
另一种选择是使用forEach循环,这为每次迭代创建一个新变量。
var gameCase = ['', '', '', '', '', '', '', '', ''], // 9
itemLists = $('game').getElementsByTagName('li'); // 9 items
itemLists.forEach(function(item,index){
item.onclick = function() {
// do something
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.