'How can I delay running a function until after jQuery get() has finished
I'm using this piece of code inside of a for loop to append some content to a div:
$.get("./" + i + "/block.html", function(data){
$(data).appendTo("#id");
});
After that, I'm using this piece of code to make the added content clickable, there's a .person div inside every block.html:
$(".person").click(function () {
$(this).toggleClass("large");
});
This second piece of code has no effect because the first piece runs asynchronously. So the content hasn't been appended yet by the time it runs. How can I delay it until it has been?
Solution 1:[1]
I wanted to add a simpler solution I found.
You can run
jQuery.ajaxSetup({async:false});
at the start to make the get() functions run synchronously. If you need them to run asynchronously for another part of the page, just run
jQuery.ajaxSetup({async:true});
to switch back to asynchronous mode afterward.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Cecemel |
