2014-02-06 76 views
0

不返回變量我試圖檢測圖像的寬度,我有網址:功能jQuery中

var getWidth = function(url){ 
    var i = new Image; 
    i.onload = function(){ 
     var width = (this.width); 
     alert(width); // width defined here 
     return width; 
    } 
    i.src = url; 
} 
var theWidth = getWidth(url); 
alert(theWidth); // undefined here 

我需要的寬度之前,我加載圖片,因此我可以修改它的容器。我覺得這裏有一個明顯的解決方案,但我無法弄清楚。謝謝!

+1

我沒有看到任何jQuery? –

+1

你不能從異步回調中返回。 –

回答

2

你不能從異步回調中返回。考慮一下。這看起來有點奇怪嗎?

function foo() { 
    setTimeout(function(){ 
     return "Hello World!"; 
    },2000) 
} 
alert(foo()); // undefined 

該函數將返回未定義,因爲它在超時之前完成。爲了解決這個問題,讓函數接受一個以所需值執行的回調函數。

function foo(callback) { 
    setTimeout(function(){ 
     callback("Hello World!"); 
    },2000) 
} 
foo(function(msg){ 
    alert(msg); // Hello World! 
}); 
+0

謝謝!我沒有意識到這一點,但它解釋它的方式是有道理的。我通過從函數內部修改圖像容器來獲得我的代碼。 – Sauce