简体   繁体   中英

Jquery: Appending data to a div AFTER ajax load operation

I have a setup much like this:

$('.container a').click(function(event) {
    event.preventDefault();
    $('#contents').remove();
    $(this).parent().append("<div id=\"contents\"></div>");
    $('#contents').html('<img src="/images/loading.gif" />')
                  .load("stuff.html")
                  .append("<div id=\"closebutton\"></div>");
});

However, the 'append' part seems to run before the load is completed, so that the closebutton div gets overwritten by the contents of stuff.html. How do I make it wait until the ajax operation has completed before performing the final append?

Thanks :)
Mala

putting append inside callback function will work.

$('.container a').click(function(event) {
    event.preventDefault();
    $('#contents').remove();
    $(this).parent().append("<div id=\"contents\"></div>");
    $('#contents').html('<img src="/images/loading.gif" />')
               .load('stuff.html',{},function(){
                  $(this).append('<div id=\"closebutton\"></div>");
               });
});

Use the callback function [The function called when the ajax request is complete (not necessarily success)] for load and then append the content.

$('#contents').html('<img src="/images/loading.gif" />')
                  .load("stuff.html",function() { AppendContent(); } )

function AppendContent()
{
    // do your append function here
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM