【问题标题】:jQuery: How to check if images have finished loading in ajaxjQuery:如何检查图像是否已在 ajax 中完成加载
【发布时间】:2012-07-13 06:08:44
【问题描述】:

我需要一些关于如何解决这个问题的建议。

当在我的页面中单击链接时,我有一个要执行的 Ajax 代码。 ajax代码是调用PHP代码查询某个目录下的图片(缩略图大小)文件名。执行后,ajax 数据将在该目录中包含我的缩略图的文件名,并在我的页面中动态显示缩略图。

我想知道如何在不使用 SetTimeOut() 的情况下检查所有缩略图是否已经完成加载?并在加载所有缩略图后执行一些 jquery 代码。我需要加载我的缩略图,以便我可以设置我的缩略图 div 的大小以进行滚动。

【问题讨论】:

    标签: php jquery ajax


    【解决方案1】:

    方法:

    function imagesLoaded(imgAr, callback){
        var 
            // This is a copy of the array of images
            imageAr = imgAr.slice(0),
            // This holds the javascript Image Objects
            images = [],
            // This is the number of Images that has loaded
            loadedCount = 0;
    
        var imageLoaded = function(){
            // An image has finished loading, so increment the number of images loaded by 1
            loadedCount++;
            if(loadedCount>=imageAr.length){
                // If all images have finished loading, run the 'callback' function, to report back that images have all loaded
                callback.call();
            }
        }
    
        // Loop around each image url
        for(var i=0;i<imageAr.length;i++){
            // For each image, create a new object
            images[i] = new Image();
            // when the image finishes loading, call the imageLoaded function
            images[i].onload = imageLoaded;
            // Assign the image the appropriate src attribute
            images[i].src = imageAr[i];
        }
    }
    

    用途:

    var imageAr = ['a.jpg', 'b.jpg', 'c.jpg'];
    
    imagesLoaded(imageAr, function(){
        alert('Images loaded!');
    });
    

    【讨论】:

    • 嗨 jeztems,对不起我的无知。这样做的目的是什么? “callback.apply({}, []);” .这是实际的代码吗?放在这一行?
    • 是的,它不应该出现在代码中,我已经编辑了原始帖子以更好地解释发生了什么。在这种情况下,“callback.apply({}, [])”的含义与“callback()”完全相同,您可以在此处阅读有关 apply 的更多信息:developer.mozilla.org/en/JavaScript/Reference/Global_Objects/…
    【解决方案2】:

    您可以对图片使用 load 方法,例如:

    $('someElement img').load(function(){
      //all loaded
    });
    

    你的意思是这样的

    【讨论】:

    • 我已经尝试过了,但似乎无法满足我的要求。 Tnx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-09
    • 2011-08-29
    • 2012-01-07
    • 2015-07-13
    • 2014-11-30
    相关资源
    最近更新 更多