2012-08-04 118 views
-1

我處於需要用這種方式解決的情況;需要將local variable轉換爲global variable。有一個例子返回圖像的真正的寬度和高度,我發現這些方法從this answer.jQuery:如何訪問外部變量?

需要將局部變量pic_real_heightpic_real_width轉換爲全局變量並返回其真實值。

Here is jsFiddle.

CSS:

img { width:0px; height:0px; }​ 

的jQuery:

console.log($('.imgCon img').height());//returns 0 

var img = $('.imgCon img')[0]; // Get my img elem 
var pic_real_width, pic_real_height; 
$('<img/>').attr('src', $(img).attr('src')).load(function() { 
     pic_real_width = this.width; 
     pic_real_height = this.height; 

     console.log(pic_real_width + 'x' + pic_real_height); 
     // -- returns true 570x320 -- 
}); 
//problem starts here: 
console.log(pic_real_width + 'x' + pic_real_height); 
//returns undefined 
// need to return this as an global variable 570x320 
+6

他們已經全球性的,但是負載發生異步的。只需在回調函數 – Bergi 2012-08-04 21:03:20

+0

中移動警報請學會使用'console.log()'而不是'alert()',主要通過在Chrome,Firefox(使用Firebug)或IE9中測試。 – 2012-08-04 21:04:38

+2

正如@Bergi所說的,一個*回調*被調用''.load()'(參見'function'部分?),並且實際上這會在*後面發生。你需要了解回調是如何工作的。 – 2012-08-04 21:06:17

回答

2

這條線,

console.log(pic_real_width + 'x' + pic_real_height);

不會等待這些線路

pic_real_width = this.width; 
    pic_real_height = this.height; 

    console.log(pic_real_width + 'x' + pic_real_height); 
    // -- returns true 570x320 -- 

執行,因爲它的異步。

因此, console.log(pic_real_width + 'x' + pic_real_height);執行前的回調函數被調用(即設置了widthheight之前)。

因爲,你還沒有定義他們,他們顯示undefined

一個平凡的解決辦法是,

$('<img/>').attr('src', $(img).attr('src')).load(function() { 
     pic_real_width = this.width; 
     pic_real_height = this.height; 

     console.log(pic_real_width + 'x' + pic_real_height); 
     // -- returns true 570x320 -- 
     restOfMyProcessing(); 

}); 

function restOfMyProcessing() { 
    console.log(pic_real_width + 'x' + pic_real_height); 
} 
+0

其工作,謝謝隊友http://jsfiddle.net/mjaA3/79/ – 2012-08-04 21:42:50

+0

不客氣,但請仔細閱讀js的異步性質以及與之相關的回調。有一天,你會做阿賈克斯的電話。 – Jashwant 2012-08-04 21:55:33

+0

我在努力學習,再次感謝。 – 2012-08-04 21:56:35

0

您嘗試他們在圖片的加載事件中設置之前,使用pic_real_width和pic_real_height。
和你的代碼一樣,第一個alert(pic_real_width + 'x' + pic_real_height)是一個圖像加載函數,它返回undefined,第二個alert在加載事件返回你的期望。
雖然這是更好的負載功能/事件後移動源屬性的設置:

$('<img/>') 
.load(function() { 
    pic_real_width = this.width; 
    pic_real_height = this.height; 

    alert(pic_real_width + 'x' + pic_real_height); 
    // -- returns true 570x320 -- 
    //now continue process here or call another function... 
}) 
.attr('src', $(img).attr('src'));