jQuery: how to access outside variable?

假装没事ソ 提交于 2019-11-28 13:55:04

问题


I am in a situation that needs be solve with this way; need convert a local variable to a global variable. There is an example returning image's real width and height which i found these method from this answer..

Need to convert local varialbes pic_real_height and pic_real_width to global variables with returning their true values.

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

回答1:


This line,

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

does not wait for these lines

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

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

to execute, because its asynchronous.

Thus, console.log( pic_real_width + 'x' + pic_real_height ); executes before callback function gets called (i.e. before you set the width and height ).

Since, you havent defined them already, they show undefined.

A trivial solution would be,

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



回答2:


You try to use pic_real_width and pic_real_height before they set in image load event.
Like in your code, first alert( pic_real_width + 'x' + pic_real_height ) is the one after image load function which returns undefined and the second alert in load event returns what you expect.
Although it's better to move setting of source attribute after load function/event:

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


来源:https://stackoverflow.com/questions/11811980/jquery-how-to-access-outside-variable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!