2012-06-11 78 views
1

尝试jQuery时,我有一个问题可能是一个新手的错误,但我似乎无法找到解决方案。这是代码:嵌套异步调用似乎没有按预期执行

$.get("index.html", function() { 
    var i = 0; 
    for (; i < 3; i++) 
    { 
     var lDiv = document.createElement('div'); 
     lDiv.id = 'body-' + i; 
     document.getElementById('body').appendChild(lDiv); 
     $.get('index.html', function(data) { 
      lDiv.innerHTML = "<p>Hello World " + i + "</p>"; 
     }); 
    } 
}); 

输出似乎

<div id='body-0'></div> 
<div id='body-1'></div> 
<div id='body-2'> 
    <p>Hello World 3</p> 
</div> 

我希望每一个我要执行的代码lDiv.innerHTML=,但显然这只是我最后一次执行?我忽略了什么?

回答

2

这是因为循环完成(i是2)之前的任何回调都被解雇。

@codeparadox的解决方案有效,但它序列化HTTP请求。 (使它们一次点燃)。这允许请求并行执行,因此更快:

for (var i = 0; i < 3; i++) 
{ 
    var lDiv = document.createElement('div'); 
    lDiv.id = 'body-' + i; 
    document.getElementById('body').appendChild(lDiv); 
    $.get('index.html', function(i,lDiv) { // the current iteration's `i` and `lDiv` are captured... 
     return function(data) { 
      lDiv.innerHTML = "<p>Hello World " + i + "</p>"; 
     } 
    }(i,lDiv)); // ...by passing them as an argument to the self-executing function 
} 
+0

我更喜欢这个解决方案,但我不得不改变它以捕获lDiv。谢谢! –

2

由于$.get()是异步的,因此您需要在$.get()success()回调函数中执行您的追加和下一个调用。

var i = 0; 
function recursiveLoad() { 
     if(i == 3) return; 
     var lDiv = document.createElement('div'); 
     lDiv.id = 'body-' + i; 
     document.getElementById('body').appendChild(lDiv); 
     $.get('index.html', function(data) { 
      lDiv.innerHTML = "<p>Hello World " + i + "</p>"; 
      i++; 
      recursiveLoad(); 
     }); 
} 
// initial call 
recursiveLoad(); 
+0

Works!我在回调函数中假设了iOS块模式的局部变量复制,这是我思考错误的地方。感谢你! –

+0

@KristofVanLandschoot欢迎您。 – thecodeparadox

+0

您在第4行末尾使用的逗号合成语法在我的解释器中不起作用。我应该将其改为“;”吗? –