总是在Array中获取最后一项,我需要一个JavaScript闭包吗?

时间:2013-01-24 13:00:54

标签: javascript jquery closures

我有一个循环遍历多维数组的函数,该数组包含我网页上某个区域的id,然后是一个我必须传递给webservice的参数。 $.ajax()调用的返回将是我希望在数组的第一部分中填充(重绘)的HTML:

function getViews(){

    // loop through, need view/jsp name and where we want to put the HTML... need a multidimarray...
    var viewArr = [["infoCol","info"], 
                   ["noteCol", "notes"],
                   ["buttonsDiv", "buttons"],
                   ["historyPanel","history"], 
                   ["servicesPanel","services"],
                   ["noFOUC","dialogs"]
                  ];

    // do the loop
    for(var i = 0;i<viewArr.length;i++){

        var thisArea = viewArr[i][0];

        $.ajax({
            url:"getView",
            type:"POST",
            data:{view:viewArr[i][1]},
            dataType:"html",
            success:function(data){
              console.log(thisArea); // this is always noFOUC
              // console.log(viewArr[i][0]); // this gives an undefined error...
                $("#" + thisArea).html(data);
            },
            error:function(xhr, ajaxOptions, thrownError){
                console.log(xhr.status);
                console.log(xhr.statusText);
                console.log(thrownError);
            }
        }); 

    }
}

现在一切都很好,但试图在成功中引用循环viewArr[i][0]的第一部分:回调不起作用!如果我把它放在成功之中:它是未定义的。如果我在上面的示例中给它一个var $.ajax()以外的值,它总是数组的最后一项!我确定我需要在这里添加一个闭包,但我不知道在哪里或为什么,有人可以解释一下吗?

如果我没有措辞或解释得这么好,请告诉我,我会更好地解释。

1 个答案:

答案 0 :(得分:3)

我认为我有这个......我在循环中放置了一个自我执行功能...... 忘了异步!循环继续...... doh!

function getViews(){

    // loop through, need view/jsp name and where we want to put the HTML... need a multidimarray...
    var viewArr = [["infoCol","info"], 
                   ["noteCol", "notes"],
                   ["buttonsDiv", "buttons"],
                   ["historyPanel","history"], 
                   ["servicesPanel","services"],
                   ["noFOUC","dialogs"]
                  ];

    // do the loop
    for(var i = 0;i<viewArr.length;i++){

        (function(){

        var thisArea = viewArr[i][0];
        $.ajax({
            url:"getView",
            type:"POST",
            data:{view:viewArr[i][1]},
            dataType:"html",
            success:function(data){
                $("#" + thisArea).html(data);
            },
            error:function(xhr, ajaxOptions, thrownError){
                console.log(xhr.status);
                console.log(xhr.statusText);
                console.log(thrownError);
            }
        }); 

        })(viewArr[i][0]);

    }
}