JQuery - 图像加载后调用函数

时间:2015-06-20 17:38:32

标签: javascript jquery image deferred

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

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)

}

2 个答案:

答案 0 :(得分:0)

这是因为您在承诺解决之前明确地呼叫resizeModal

loadImage(imgSrc).done( resizeModal() )

foo(bar())一样,这会调用resizeModal并将其返回值传递给done()

您想要传递函数本身:

loadImage(imgSrc).done(resizeModal)

这基本上意味着一旦你完成了#34;就打电话给resizeModal

答案 1 :(得分:-1)

O(n)

您是否尝试过这样的结构?