简体   繁体   English

Jquery:在ajax加载操作后将数据附加到div

[英]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. 但是,'append'部分似乎在加载完成之前运行,因此closebutton div被stuff.html的内容覆盖。 How do I make it wait until the ajax operation has completed before performing the final append? 在执行最终追加之前,如何让它等到ajax操作完成?

Thanks :) 谢谢 :)
Mala 马拉

putting append inside callback function will work. append置于回调函数中将起作用。

$('.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. 使用回调函数 [当ajax请求完成时调用的函数 (不一定成功)]进行加载,然后附加内容。

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

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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