在jquery追加后运行函数

时间:2014-06-21 01:52:57

标签: javascript jquery ajax dom

我有此功能可以将更多图片帖子插入我的网页。插入图像后,其中包含图像的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);
                }
            });
        }
    });
}

3 个答案:

答案 0 :(得分:1)

您可以使用图片上的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);
    });
  }
});

答案 1 :(得分:0)

在加载图像时会触发img标记上的onload事件。你试过这个吗?

$(document).on('load', 'img', function(){
// resize
});

您还需要检查完整属性并触发加载事件(如果为真)

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

答案 2 :(得分:0)

除了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);
                     });
                 }
             });
         }
     });
 }
相关问题