我處於需要用這種方式解決的情況;需要將local variable
轉換爲global variable
。有一個例子返回圖像的真正的寬度和高度,我發現這些方法從this answer.。jQuery:如何訪問外部變量?
需要將局部變量pic_real_height
和pic_real_width
轉換爲全局變量並返回其真實值。
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
他們已經全球性的,但是負載發生異步的。只需在回調函數 – Bergi 2012-08-04 21:03:20
中移動警報請學會使用'console.log()'而不是'alert()',主要通過在Chrome,Firefox(使用Firebug)或IE9中測試。 – 2012-08-04 21:04:38
正如@Bergi所說的,一個*回調*被調用''.load()'(參見'function'部分?),並且實際上這會在*後面發生。你需要了解回調是如何工作的。 – 2012-08-04 21:06:17