简体   繁体   English

加载div中的每个图像后,运行一个函数

[英]Run a function once every image in a div has loaded

Say I have this markup 说我有这个标记

<div id="imageDiv">
    <img src="/img/1.jpg" />
    <img src="/img/2.jpg" />
    <img src="/img/3.jpg" />
    <img src="/img/4.jpg" />
    <img src="/img/5.jpg" />
</div>

What I want to do is run a function, but only after all the images have loaded in. Now, I haven't any actual code to show, but the only way I can see to do this is this (psuedo-code, so untested) 我想做的是运行一个函数,但仅在加载完所有图像之后。现在,我没有任何实际的代码可显示,但是我能看到的唯一方法是执行此操作(伪代码,因此未经测试)

function imagesReady(){
    $.each(imageReady, function(key, val){
        if (!val){
            return;
        }
    });
    nowDoTheMainFunction();
}
var imageReady = [];
$.each(imageDiv, function(key,imageElement){
    imageReady[key] = false;
    imageElement.addLoadListener(function(){
        imageReady[key] = true;
        imagesReady();
    });
});

Is there a neater/better way than that to do this? 有没有比这更整洁/更好的方法了?

You may try this: 您可以尝试以下方法:

$(window).on('load', function() {
    nowDoTheMainFunction();
});

The best way I think to be able to do this is do use JQuery onload function . 我认为能够做到这一点的最佳方法是使用JQuery onload function

$( "#imageDiv" ).load(function() {
    // once the images have loaded
});

This will wait until images have loaded before any of the function is able to run. 这将等到图像加载完毕后,任何功能才能运行。

The easiest way is to use the window.onload event. 最简单的方法是使用window.onload事件。 This won't fire until all of the resources, including CSS and Images, have loaded and are ready. 直到所有资源(包括CSS和图像)均已加载并准备就绪,这才会触发。

This must do what you are trying to accomplish 这必须做您想完成的事情

$("#imageDiv img").one('load', function () {
        // Your code
    }).each(function () {
        if (this.complete) $(this).load();
    });

This might not be the thing you are looking for but out of curiosity, I made something. 这可能不是您要查找的东西,但是出于好奇,我做了一些事情。 May be it will help you. 可能会对您有帮助。

Demo 演示

HTML: HTML:

<div id="imageDiv"></div>

Js: JS:

var sources = ['http://i.imgur.com/qNRcqpo.jpg?1', 'http://i.imgur.com/iXTvWhX.jpg']  ;
var images = {};
    var loadedImages = 0;
    var numImages = sources.length;


    for (var src in sources) {
        images[src] = document.createElement("img");;
        images[src].id = src;
        images[src].onload = function () {

            if (++loadedImages >= numImages) {
                functionTobeCalled();
            }

        };
        images[src].src = sources[src];
         $('#imageDiv').append(images[src]);
    }

function functionTobeCalled (){
alert('all images loaded');
}

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

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