2015-06-20 73 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'回调中吗? –