简体   繁体   English

jQuery-图像加载后调用功能

[英]JQuery - Calling function after image load

So I have two functions. 所以我有两个功能。 One to load the image and the other to resize its container element. 一个加载图像,另一个调整其容器元素的大小。 Naturally the image element needs to be loaded, before any measurements can be taken. 自然,需要先加载图像元素,然后才能进行任何测量。 It looks something like this: 看起来像这样:

var imgEl;

loadImage(imgSrc);
// only call the below, once the above has finished loading and appending the image.
resizeModal();

function loadImage(imgSrc) {
    var image = new Image();
    image.src = imgSrc;
    image.onload = function() {
        imgEl = $('<img src='+image.src+'/>');
        imgEl.prependTo(modal); 
    }
}

function resizeModal() {

    // Do stuff based off the imgEl once it's been loaded and appended 
    var width = imgEl.width();
    modal.width(width)

}

I've tried using $.Deferred, but I'm apparently missing something, as "B" always gets logged before "A": 我尝试使用$ .Deferred,但是我显然缺少了一些东西,因为“ B”总是在“ A”之前被记录:

var imgEl;

loadImage(imgSrc).done( resizeModal() )

function loadImage(imgSrc) {

    var def = $.Deferred();

    var image = new Image();
    image.src = imgSrc;
    image.onload = function() {
        imgEl = $('<img src='+image.src+'/>');
        imgEl.prependTo(modal); 

        console.log("A");
        def.resolve();

    }

    return def;
}

function resizeModal() {

    console.log("B");

    // Do stuff based off the imgEl once it's been loaded and appended 
    var width = imgEl.width();
    modal.width(width)

}

That's because you are explicitly calling resizeModal before the promise is resolved: 那是因为您解决承诺之前明确地调用了resizeModal

loadImage(imgSrc).done( resizeModal() )

Just like with foo(bar()) , this will call resizeModal and pass its return value to done() . 就像foo(bar()) ,这将调用resizeModal并将其返回值传递给done()

You want to pass the function itself instead: 您想改为传递函数本身:

loadImage(imgSrc).done(resizeModal)

This basically means "call resizeModal once you are done". 这基本上意味着“完成后调用resizeModal ”。

var loadImage = function(imgSrc, callback) {
    var imgEl;
    var image = new Image();
    image.src = imgSrc;
    image.onload = function() {
        imgEl = $('<img src='+image.src+'/>');
        imgEl.prependTo(modal); 
    }
    callback(imgEl);
}

var resizeModal = function(imgEl) {
    // Do stuff based off the imgEl once it's been loaded and appended 
    var width = imgEl.width();
    modal.width(width)
    return width;  // or whatever you are trying to get from this.
}

var finalOutput = loadImage(imgSrc, resizeModal);

Have you tried a structure like this? 您是否尝试过这样的结构?

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

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