2015-06-20 78 views
0

所以我有兩個函數。一個加載圖像,另一個調整其容器元素的大小。在進行任何測量之前,圖像元素自然需要加載。它看起來是這樣的:JQuery - 圖片加載後調用函數

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) 

} 
+0

由於圖像需要時間加載,所以當您執行'resizeModal'時,圖像可能尚未加載。所以把'resizeModal()'放到'image.onload'中。 – fuyushimoya

+0

@fuyushimoya:這就是爲什麼OP使用承諾的全部觀點。 –

+0

@FelixKling他第一次嘗試的方式不是關於承諾,我的評論是關於它的第一部分代碼,是否有任何問題? – fuyushimoya

回答

0

這因爲你是顯式調用resizeModal之前的承諾得到解決:

就像使用 foo(bar())
loadImage(imgSrc).done(resizeModal()) 

,這將請致電resizeModal並將其返回值傳遞給done()

你想通過函數本身,而不是:

loadImage(imgSrc).done(resizeModal) 

這基本上意味着「呼resizeModal一旦你完成」。

+0

啊,有趣,好吧。那在「B」之前記錄了「A」,但這讓我想知道 - 如何將這些解析爲resizeModal? – nomis101uk

+0

將值傳遞給'.resolve':'def.resolve(theValueToPassAlong)'。請參閱https://api.jquery.com/deferred.resolve/ –

+1

這可能更有幫助,即使它不是關於jQuery的promise/deferred實現:http://www.html5rocks.com/en/tutorials/es6/promises/ –

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

你試過這樣的結構嗎?

+0

這與OP的第一個例子基本相同。你的意思是把'callback(imgEl);'*放在'load'回調中嗎? –