在for循环中构造时,只返回数组的最后一个值

时间:2014-06-19 08:57:09

标签: javascript jquery arrays

我遇到此功能的问题:

var url = "";

function multiSearchTest() {
    var formData = $("#frmSearch").serialize();
    var look = new Array("SDO", "AR", "AS", "AC", "AP", "GEMO", "CC");
    var count;

    for(count = 0; count < look.length; count++){
       url = "index.php?Page&module=mod_page&action=dispatch&todo=cerca"+look[count]+"&" + formData;
       console.log(url);
    var test = "#"+look[count]+"result";

    $.get(url, function(data) {
           $(test).html(data);
           console.log("TEST VAL => " + test);
        });
    }
}

正如你所看到的那样,url构造是完美的...但是当我说打印输出的位置时,它只返回数组的最后一个val。有什么想法或建议吗?我的错误在哪里?

1 个答案:

答案 0 :(得分:2)

var test之外声明forloop。并将其设为数组。因为var test for loop每次创建一个新对象,所以在for循环之外声明变量test

 function multiSearchTest() {
        var formData = $("#frmSearch").serialize();
        var look = new Array("SDO", "AR", "AS", "AC", "AP", "GEMO", "CC");
        var count;
    var test = [];

        for(count = 0; count < look.length; count++){
           url = "index.php?Page&module=mod_page&action=dispatch&todo=cerca"+look[count]+"&" + formData;
           console.log(url);
           test[count] = "#"+look[count]+"result";

        $.get(url, function(data) {
               $(test[count]).html(data);
               console.log("TEST VAL => " + test[count]);
            });
        }
    }