3

嗨,我正在使用 ajax 和 json 进行无限滚动,然后我创建一个 html 字符串添加到我的网页并使用 jQuery 的 after() 函数调用它。

  $('.product-panel:last').after(productHTML);

现在我需要等待我的新 productHTML 字符串中的所有图像加载,然后调用我创建的另一个 javascript 函数来进行一些格式化。

我试过了

         $('.product-panel:last').after(productHTML).promise().done(function(){
             doMoreStuff();
         }); 

它不起作用。有人可以帮忙吗?谢谢

编辑:遵循 adeneo 的代码后,这是我的最终结果,它完美无缺。

    var productLength = $('.product-panel').length-1;
    $('.product-panel:last').after(productHTML);
    var images   = $(".product-panel:gt("+productLength+")").find('img');
    var promises = [];

    images.each(function(idx, img) {
        var def = $.Deferred();

        img.onload  = def.resolve;
        img.onerror = def.reject;

        if ( img.complete ) def.resolve();

        promises.push(def.promise());
    });

    $.when.apply($, promises).done(function() {
       productHeight();
    });
4

2 回答 2

1

这不是那么容易,您必须找到所有插入的图像并等待它们单独加载,就像这样

var images   = $('.product-panel:last').after(productHTML).next().find('img');
var promises = [];

images.each(function(idx, img) {
    var def = $.Deferred();

    img.onload  = def.resolve;
    img.onerror = def.reject;

    if ( img.complete ) def.resolve();

    promises.push(def.promise());
});

$.when.apply($, promises).done(function() {
    // all images loaded
});
于 2015-08-15T18:19:23.363 回答
0

似乎这对我有用

我从 json 生成我的 html,我放置了一个 imageCount 变量,然后将这个用于 imagesLoaded 的计数器设置为 0。然后在每次图像加载后调用 $(img).load() 函数,然后我继续检查查看 imageCount 和 imagesLoaded 是否相同。

    var imagesLoaded = 0;
    $('.product-panel:last').after(productHTML);
    $('img').load( function() {
        imagesLoaded++;
        if(imagesLoaded == imageCount){
            console.log("all images loaded");
            productHeight();
        }
    });
于 2015-08-15T19:34:21.870 回答