简体   繁体   中英

Setting a global scope variable inside a function

I'm trying to setup animation triggers based on the height of the element. The project is built with AngularJS, but the problem I'm having seems really bizzare. I'm trying to set an imgH variable when the image loads. Inside my onload function the log returns the correct image height and sets the global variable imgH. After my onload function the console log command returns imgH = undefined

var imgH;
        $('.step-image').on('load',function(){
            imgH = $(this).height();
            console.log(imgH);
        });
console.log(imgH);

The variable is getting set, it's just not yet set when you do that console.log at the end.

Here's the sequence in which your code runs:

  1. var imgH; - Creates the global with an initial value of undefined .
  2. $('.step-image').on('load', function ...) - Sets up the handler, doesn't (yet) call the function.
  3. console.log(imgH); (at the bottom) - Shows undefined because nothing has assigned a value to imgH yet.
  4. Later , when the image loads, the handler function is called and sets imgH .
  5. console.log(imgH); (inside the handler function) - Shows the value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM