jQuery: how to access outside variable?

后端 未结 2 1873
余生分开走
余生分开走 2020-12-22 12:40

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 r

相关标签:
2条回答
  • 2020-12-22 13:26

    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 );
    }
    
    0 讨论(0)
  • 2020-12-22 13:35

    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'));
    
    0 讨论(0)
提交回复
热议问题