jQuery Deferred-延迟getJSON成功函数中的变量范围 [英] jQuery Deferred - Variable scope in deferred getJSON success functions
问题描述
我正在将延迟的getJSON调用添加到for循环内的数组中,该循环引用其成功函数内的局部变量.我遇到的问题是,当调用成功函数时,局部变量将从循环的上一次迭代中获取值.参见以下示例:
I am adding deferred getJSON calls to an array inside a for loop that reference local variables inside their success function. The problem I am having is that when the success function is called, the local variable is taking the value from the last iteration of the loop. See below example:
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/
jsFiddle: http://jsfiddle.net/Me5rV/
这将导致三个警报,其值为"c",而我希望值为"a","b"和"c".这可能吗?
This results in three alerts with the value 'c', whereas I would like the values 'a', 'b', and 'c'. Is this possible?
以下方法有效,但是我不完全确定为什么会有所不同?
The below works, but I'm not entirely sure why this differs?
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/
jsFiddle: http://jsfiddle.net/Me5rV/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
现在您可以改为执行此操作(删除重复项):
Now you could do this instead (repetition removed):
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));
这篇关于jQuery Deferred-延迟getJSON成功函数中的变量范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!