jQuery:如何访问外部变量?

我处在一种需要用这种方式解决的情况; 需要将local variable转换为global variable 。 有一个例子返回图像的真实宽度和高度,我从这个答案中找到了这些方法

需要将本地变量pic_real_heightpic_real_width转换为全局变量并返回其真值。

这是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; $('').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 

这条线,

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

一个简单的解决方案是,

 $('').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 ); } 

在图像加载事件中设置之前,您尝试使用pic_real_width和pic_real_height。
就像你的代码一样,第一个alert( pic_real_width + 'x' + pic_real_height )是图像加载函数之后的一个返回undefined ,而load事件中的第二个alert返回你期望的。
虽然最好在加载函数/事件后移动source属性的设置:

 $('') .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'));