`for循环中的`jQuery.getJSON()`函数 [英] `jQuery.getJSON()` function inside a for loop
本文介绍了`for循环中的`jQuery.getJSON()`函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有以下代码返回 h = 30
而不是循环中的每个值。
I have the following code which returns h=30
instead of each value inside the loop.
for (var h = 0; h < 31; h++) {
$.getJSON('http://google.com/',
function(data) {
console.log('line ' + h);
}
)
};
我需要做什么才能获得循环值?
What do I need to do to get loop values?
推荐答案
使用 IIFE
for (var h = 0; h < 31; h++) {
(function(h) {
$.getJSON('http://google.com/', function(data) {......
console.log('line ' + h);
})
})(h)
};
这样, h
的值将会保留该迭代,而不是在 getJSON
被回调时被设置为最后一个值
That way, the value of h
will be preserved for that iteration instead of being set to the last value by the time getJSON
is called back
这篇关于`for循环中的`jQuery.getJSON()`函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文