所以我有兩個函數。一個加載圖像,另一個調整其容器元素的大小。在進行任何測量之前,圖像元素自然需要加載。它看起來是這樣的: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)
}
由於圖像需要時間加載,所以當您執行'resizeModal'時,圖像可能尚未加載。所以把'resizeModal()'放到'image.onload'中。 – fuyushimoya
@fuyushimoya:這就是爲什麼OP使用承諾的全部觀點。 –
@FelixKling他第一次嘗試的方式不是關於承諾,我的評論是關於它的第一部分代碼,是否有任何問題? – fuyushimoya