【问题标题】:jQuery Deferred - Variable scope in deferred getJSON success functionsjQuery Deferred - 延迟 getJSON 成功函数中的变量范围
【发布时间】:2012-08-10 22:46:08
【问题描述】:

我正在将延迟的 getJSON 调用添加到 for 循环内的数组中,该数组在其成功函数中引用局部变量。我遇到的问题是,当调用成功函数时,局部变量正在从循环的最后一次迭代中获取值。见下例:

var calls = [];
var arr = ['a','b','c'];
for (var a in arr) {
    calls.push(
        $.getJSON(window.location, function() { alert(arr[a]); })
    );
}
$.when.apply($,calls);

jsFiddle:http://jsfiddle.net/Me5rV/

这会产生三个值为“c”的警报,而我想要值“a”、“b”和“c”。这可能吗?

编辑:以下内容有效,但我不完全确定为什么会有所不同?

var calls = [];
var arr = ['a','b','c'];
for (var a in arr) {
    calls.push(
        $.getJSON(window.location, function(x) {
            alert(x);
       }(arr[a]))
    );
}
$.when.apply($,calls);

jsFiddle:http://jsfiddle.net/Me5rV/1/

【问题讨论】:

  • 似乎是这样,虽然我不完全理解这里的问题,但我使用相同的解决方案让它工作。谢谢。
  • 如果其他问题还不够,我想我可以解释一下......秒

标签: jquery getjson jquery-deferred


【解决方案1】:

回顾一下这样的循环:

var a = [];

for( var i = 0; i < 3; ++i ) {
    a.push( function() {
        alert(i);
    });
}

确实如此:

var a = [], i = 0;

a.push( function(){
    alert(i);
});

i++;

a.push( function() {
    alert(i);
});

i++;

a.push( function() {
    alert(i);
});

i++;

//condition isn't met, loop terminates

alert(i) //alerts 3 because i is 3 now.
         //That's why all the functions alert 3, because they all 
         //refer to this i and its value is 3

现在您可以改为这样做(删除重复):

a.push( function(i){
    return function() {
         alert(i); //Refers to the i passed as argument to the outer function
                   //not the global one
                   //The local i has whatever value the global i had when it was passed
                   //as argument
    };
}(i));

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-10-19
    • 2011-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-03-30
    相关资源
    最近更新 更多