Javascript onclick shows last element of array with for loop

后端 未结 3 1214
粉色の甜心
粉色の甜心 2021-01-14 13:21

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.r         


        
相关标签:
3条回答
  • 2021-01-14 13:47

    If you don't care about IE8- then ES5 already solves this issue with forEach:

    activities.forEach(function(v, i){
      // now 'i' will work anywhere within this scope
    });
    
    0 讨论(0)
  • 2021-01-14 13:52

    This is yet another case of closure problems. Try this:

    for( i=0; i<activities.length; i++) {
        (function(i) {
            // your code here
        })(i);
    }
    
    0 讨论(0)
  • 2021-01-14 13:52

    Move the guts of the for loop out to a function, and pass in the values that need to be scoped separately.

    for(i=0; i < activities.length; i++) {
        setUpActivity(i, activities[i]);
    }
    

    function setUpActivity(i, activity) {
    
        activity.onStart(function() { alert(i+ " started"); });
        activity.onCredit(function() { alert(i+ " credit"); });
        activity.onClose(function() { alert(i+ " close"); });
        activity.onFinish(function() { alert(i+ " finish"); });
        ARNO.box.show({
            html:'<div id="socialVibeFancyBox0"></div>', 
            close: false, width:activity.window_width, 
            height:activity.window_height, 
            openjs:function(){
                        client.loadActivityIntoContainer(activity, 'socialVibeFancyBox0');
                    }
                });
    }
    

    A function invocation creates a new variable scope. any variables or parameters created in the function will be in their own scope, and the functions created in the same scope will have permanent reference to those variables.

    0 讨论(0)
提交回复
热议问题