问题描述
我尝试使用 for 创建循环,并通过 onclick 事件递增,但它不起作用.
I've tried to create a loop with a for, and increment by an onclick event, but it doesn't work.
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 循环在我能够单击列表中的元素之前已经完成.
But in this case, the For loop is already finished before I was able to click on an element of the list.
此外,我想获取我单击的项目列表并将其保存在数组中.我尝试了一个 gameCase[this](在 onclick 函数中),但我不知道这是不是好方法.
Moreover, I would like to get the item list I clicked and save it on a the array. I tried a gameCase[this] (in onclick function), but I don't know if it's the good way.
推荐答案
John Resig 在JavaScript Ninja 的秘密"( http://ejohn.org/apps/learn/#59 )
John Resig covers this topic very well in "Secrets of the JavaScript Ninja" ( http://ejohn.org/apps/learn/#59 )
你需要创建一个临时作用域来保存 i 的值
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);
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.
这篇关于For 循环中的 onClick 事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!