Nested asynchronous calls do not seem to execute as expected
- by Kristof Van Landschoot
While trying out jQuery, I have a question that is probably a newbie mistake, but I cannot seem to find the solution. This is the code:
$.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>";
});
}
});
The output seems to be
<div id='body-0'></div>
<div id='body-1'></div>
<div id='body-2'>
<p>Hello World 3</p>
</div>
I expected the lDiv.innerHTML= code to be executed for each i, but apparently it is only executed for the last i? What am I overlooking?