所以我有两个函数。一个加载图像,另一个调整其容器元素的大小。在进行任何测量之前,图像元素自然需要加载。它看起来是这样的: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