[英]`jQuery.getJSON()` function inside a for loop
I have the following code which returns h=30
instead of each value inside the loop. 我有以下代码,它返回
h=30
而不是循环内的每个值。
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? 我需要怎么做才能获得循环值?
Make a closure with an IIFE 用IIFE封闭
for (var h = 0; h < 31; h++) {
(function(h) {
$.getJSON('http://google.com/', function(data) {......
console.log('line ' + h);
})
})(h)
};
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 这样,将为该迭代保留
h
的值,而不是在调用getJSON
h
将其设置为最后一个值
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.