JQuery - 图片加载后调用函数

JQuery - Calling function after image load

所以我有两个功能。一个加载图像,另一个调整其容器元素的大小。在进行任何测量之前,自然需要加载图像元素。它看起来像这样:

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)

}

我试过使用 $.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)

}

那是因为您在 承诺解决之前显式调用 resizeModal :

loadImage(imgSrc).done( resizeModal() )

就像 foo(bar()) 一样,这将调用 resizeModal 并将其 return 值传递给 done()

您想传递函数本身:

loadImage(imgSrc).done(resizeModal)

这基本上意味着"call resizeModal once you are done"。

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);

你试过这样的结构吗?