Javascript onclick使用for循环显示数组的最后一个元素 [英] Javascript onclick shows last element of array with for loop
问题描述
我没什么问题.我正在使用一家公司的API.我要求参加活动,他们还给我一系列活动.这是代码的一部分.
I have little problem. I am working with one companys API's. I request for activities and they return me array of activities. Here is part of code.
client.requestActivities(function(activities) {
if (activities.length > 0) {
for(i=0; i < activities.length; i++) {
var activity = activities[i];
activity.onStart(function() { alert(i+ " started"); });
activity.onCredit(function() { alert(i+ " credit"); });
activity.onClose(function() { alert(i+ " close"); });
activity.onFinish(function() { alert(i+ " finish"); });
$('.Game-Screen-Footer').append('<div class="Game-Screen-Footer-Adv" id="foota'+i+'"><a href="javascript:;" ><img src="'+activity.image_url+'" alt="'+activity.display_text+'" width="190" height="110"></a></div>');
document.getElementById('foota'+i+'').onclick = function() {
ARNO.box.show({html:'<div id="socialVibeFancyBox0"></div>', close: false, width:activity.window_width, height:activity.window_height, openjs:
function(){
client.loadActivityIntoContainer(activity, 'socialVibeFancyBox0');
}
});
}
}
}
通常,此函数返回具有3个元素的数组.但是,当我单击第一个活动时,onStart应该会提醒我(0个开始),但是会提醒我(4个开始),这意味着,它警告了i的最后一个元素.我该如何解决?我尝试了很多东西,但是我没有找到解决方案,也许您可以帮我吗?
Mostly, this function give back array with 3 elements. But when I click on first activity, onStart it should alert me (0 start), but it alerts (4 start), this means, that it alerts last element of i. How should I fix this? I tried a lot of stuff, but I haven't find solution, maybe you can help me?
推荐答案
这是关闭问题的另一种情况.试试这个:
This is yet another case of closure problems. Try this:
for( i=0; i<activities.length; i++) {
(function(i) {
// your code here
})(i);
}
这篇关于Javascript onclick使用for循环显示数组的最后一个元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!