闭包里面一个for循环 - 回调循环变量作为参数 [英] closure inside a for loop - callback with loop variable as parameter
问题描述
我在循环中使用jQueryGET从服务器获取几个结果。我想将循环索引作为回调的固定参数,但它不工作。
I am using jQuery "GET" in a loop to obtain several results from the server. I want to include the loop index as a fixed parameter to the call back but its not working.
(我遵循这篇文章。)
但是,我在回调中获得的值完全不是我的期望 - 而不是每个循环索引值,它总是等于索引的退出值。
However, the value I get in the call back is completely not what I expect – rather than each loop index value, it is always equal to the exit value of the index.
即。这里的代码片段为每次执行回调打印出'16'。如何让它打印1,2,3 ...(我意识到顺序可能不同,很好)
ie. the code fragment here prints out '16' for each execution of the callback. How do I get it to print 1, 2, 3... (I realize the order might be different, that's fine)
除了下面的代码,我已经尝试了几种方法来指定回调函数,例如。 function(data,textStatus){return test(data,textStatus,idx);
In addition to the code below, I've tried several ways to specify the call back function, eg. function(data, textStatus) { return test(data, textStatus, idx); }, 'text');
etc.
How is this supposed to work?
function test(data, textStatus, siteNo)
{
console.log("siteNo=" + siteNo);
}
function loadConfigLists()
{
var siteReport;
// retrieve site configuration
jQuery.get("svGetSiteConfig.php", function(data, textStatus)
{
// retrieve port configuration for all sites
for (var idx=1; idx<=15; idx++)
{
var probeIP = siteConfigArray[idx].siteIP;
if (probeIP != "" && probeIP != null)
jQuery.get("svGetPortInfo.php?svSiteIpAddr=" + probeIP+"&s="+idx,
function(data, textStatus) { test(data, textStatus, idx); }, 'text');
else // IP value is blank
siteConfigArray[idx].portManifest = null;
}
}
}, 'text');
}
推荐答案
与封闭。当你这样做:
function(data, textStatus) { test(data, textStatus, idx); }
您绑定了 idx
但不是 idx
的值。所以,当你的回调被调用时,循环将完成,并且 idx
在你绑定的所有回调中都为16。
You're binding a reference to idx
but not to the value of idx
. So, by the time your callback gets called, the loop will have finished and idx
will be 16 in all of the callbacks that you bound.
通常的解决方案是通过函数调用强制执行 idx
的评估:
The usual solution is to force evaluation of idx
through a function call:
function build_callback(idx) {
return function(data, textStatus) {
test(data, textStatus, idx);
};
}
// And then...
jQuery.get("svGetPortInfo.php?svSiteIpAddr=" + probeIP+"&s="+idx, build_callback(idx), 'text');
如果要将它们保存在一起,还可以使用自动执行函数来内联函数:
You can also inline the function with a self-executing function if you want to keep it all together:
for (var idx=1; idx<=15; idx++)
(function(idx) {
var probeIP = siteConfigArray[idx].siteIP;
if (probeIP != "" && probeIP != null)
jQuery.get("svGetPortInfo.php?svSiteIpAddr=" + probeIP+"&s="+idx,
function(data, textStatus) { test(data, textStatus, idx); }, 'text');
else // IP value is blank
siteConfigArray[idx].portManifest = null;
})(idx);
函数调用给你 idx
当函数被调用时,它是 idx
的值。
The function call gives you the value of idx
when the function is called and that's the value of idx
that you want.
这篇关于闭包里面一个for循环 - 回调循环变量作为参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!