Javascript 在jquery追加后运行函数

Javascript 在jquery追加后运行函数,javascript,jquery,ajax,dom,Javascript,Jquery,Ajax,Dom,我有这个功能,可以在我的网页中插入更多的图片帖子。插入图像后,包含图像的div大小将调整为与图像相同的宽度。然而,我遇到的问题是,它是在加载图像之前运行的,因此没有调整div的大小 你知道我如何设置它在所有图像加载后运行吗 function load_more(url, page, page_name) { $.ajax({ type: 'POST', url: "/app/load_more/" + page_name + "/pagename/" +

我有这个功能,可以在我的网页中插入更多的图片帖子。插入图像后,包含图像的div大小将调整为与图像相同的宽度。然而,我遇到的问题是,它是在加载图像之前运行的,因此没有调整div的大小

你知道我如何设置它在所有图像加载后运行吗

function load_more(url, page, page_name) {
    $.ajax({
        type: 'POST',
        url: "/app/load_more/" + page_name + "/pagename/" + url,
        data: 'id=testdata',
        dataType: 'json',
        cache: false,
        success: function (data) {
            $(".next").remove();
            $("#top").append(data['top']);
            $("#bottom").append(data['bottom']);
            $('.img-wrap').each(function () {
                if ($(this).find('img').attr('src') != "") {
                    $(this).animate({
                        width: $(this).find('img').css("width")
                    }, 300);
                }
            });
        }
    });
}

img标记上有一个onload事件,该事件在图像加载时触发。你试过这个吗

$(document).on('load', 'img', function(){
// resize
});
您还需要检查complete属性,如果为true,则触发load事件

var $img = $(this).find('img'); 
if ($(this).find('img').attr('src') != "" && $img.get(0).complete){
    $img.trigger('load);
}

您可以在图像上使用
load
事件等待加载:

$('.img-wrap').each(function() { 
  var div = $(this);
  var img = div.find('img');
  if (img.attr('src') != ""){
    img.on('load', function(){
      div.animate({
        width: img.css("width")
      }, 300);
    });
  }
});

除了Guffa提到的,我甚至可能将代码中不依赖数据的部分移动到.ajax完全回调中:

 function load_more(url, page, page_name) {
     $.ajax({
         type: 'POST',
         url: "/app/load_more/" + page_name + "/pagename/" + url,
         data: 'id=testdata',
         dataType: 'json',
         cache: false,
         success: function (data) {
             $(".next").remove();
             $("#top").append(data['top']);
             $("#bottom").append(data['bottom']);
         },
         complete: function () {
             $('.img-wrap').each(function () {
                 var div = $(this);
                 var img = div.find('img');
                 if (img.attr('src') != "") {
                     img.load(function () {
                         div.animate({
                             width: img.css("width")
                         }, 300);
                     });
                 }
             });
         }
     });
 }