在函数内设置全局范围变量

时间:2022-05-02 00:41:52

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

我正在尝试根据元素的高度设置动画触发器。该项目是使用AngularJS构建的,但我遇到的问题看起来真的很奇怪。我正在尝试在图像加载时设置imgH变量。在我的onload函数中,日志返回正确的图像高度并设置全局变量imgH。在我的onload函数之后,console log命令返回imgH = undefined

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

1 个解决方案

#1


2  

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

变量已设置,当你在最后执行console.log时,它还没有设置。

Here's the sequence in which your code runs:

这是代码运行的顺序:

  1. var imgH; - Creates the global with an initial value of undefined.
  2. var imgH; - 创建初始值为undefined的全局。

  3. $('.step-image').on('load', function ...) - Sets up the handler, doesn't (yet) call the function.
  4. $('。step-image')。on('load',function ...) - 设置处理程序,但尚未调用该函数。

  5. console.log(imgH); (at the bottom) - Shows undefined because nothing has assigned a value to imgH yet.
  6. 的console.log(IMGH); (在底部) - 显示未定义,因为还没有为imgH分配值。

  7. Later, when the image loads, the handler function is called and sets imgH.
  8. 稍后,当图像加载时,调用处理函数并设置imgH。

  9. console.log(imgH); (inside the handler function) - Shows the value.
  10. 的console.log(IMGH); (在处理函数内) - 显示值。

#1


2  

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

变量已设置,当你在最后执行console.log时,它还没有设置。

Here's the sequence in which your code runs:

这是代码运行的顺序:

  1. var imgH; - Creates the global with an initial value of undefined.
  2. var imgH; - 创建初始值为undefined的全局。

  3. $('.step-image').on('load', function ...) - Sets up the handler, doesn't (yet) call the function.
  4. $('。step-image')。on('load',function ...) - 设置处理程序,但尚未调用该函数。

  5. console.log(imgH); (at the bottom) - Shows undefined because nothing has assigned a value to imgH yet.
  6. 的console.log(IMGH); (在底部) - 显示未定义,因为还没有为imgH分配值。

  7. Later, when the image loads, the handler function is called and sets imgH.
  8. 稍后,当图像加载时,调用处理函数并设置imgH。

  9. console.log(imgH); (inside the handler function) - Shows the value.
  10. 的console.log(IMGH); (在处理函数内) - 显示值。