简体   繁体   English

无法访问 function 内的全局变量(Javascript)

[英]Can't access global variables inside a function (Javascript)

I wrote a simple BMI calculator, but I seem to be unable to access global variables inside the function. If weight is only a number, everything is okay--but when I want to get this element with Javascript, it doesn't work.我写了一个简单的BMI计算器,但我似乎无法访问function内部的全局变量。如果weight只是一个数字,一切都很好——但是当我想用Javascript获取这个元素时,它不起作用。 When those variables are inside a function, everything works excellent.当这些变量在 function 中时,一切都很好。 I know, hoisting, scope.. but why do variables with numbers work then?我知道,提升,scope.. 但是为什么带有数字的变量可以工作呢?

Here is the code:这是代码:

const height = parseInt(document.querySelector("#height").value);
const weight = parseInt(document.querySelector("#weight").value);

const results = document.querySelector("#results");

function bmiCalc() {
  if (height === "" || isNaN(height))
    results.innerHTML = "Invalid Height! Please use numbers";
  else if (weight === "" || isNaN(weight))
    results.innerHTML = "Invalid Weight! Please use numbers";
  else {
    const bmi = (weight / ((height * height) / 10000)).toFixed();
    results.innerHTML = bmi;
  }
}

const button = document.querySelector(".results__btn");

button.addEventListener("click", bmiCalc);

The reason is that, when the page loads, your global variables will read the input before anything is entered.原因是,当页面加载时,您的全局变量将在输入任何内容之前读取输入。 Global variables are created when the page load and deleted when the window is closed.全局变量在页面加载时创建,在 window 关闭时删除。 In your code, the global variables weight and height are being created and they are assigned a value with these two inputs(which is empty).在您的代码中,正在创建全局变量 weight 和 height 并使用这两个输入(为空)为它们分配一个值。 So, when you click the button, the weight and height variables has the value of "".因此,当您单击该按钮时,体重和身高变量的值为“”。 Instead of showing the evaluated result, it will show you the error message.它不会显示评估结果,而是会显示错误消息。 In the other hands, when you put the variables inside the function, the variable will not be created unless you execute the function (in this case, it is the bmiCalc function).另一方面,当您将变量放入 function 时,除非您执行 function(在本例中为 bmiCalc 函数),否则不会创建该变量。 This is how it works:它是这样工作的:

  1. The button is clicked按钮被点击
  2. The variable gets created.变量被创建。
  3. The function evaluates the inputs. function 评估输入。
  4. It displays the result when the conditions are met.当条件满足时显示结果。
  5. The function ends. function结束。
  6. The variables gets deleted.变量被删除。

And, the same process happens over and over again.而且,同样的过程一遍又一遍地发生。

that is because you are fetching the value before the user enters anything, because the input data is fetched once script starts running那是因为您在用户输入任何内容之前获取值,因为一旦脚本开始运行就会获取输入数据

You need to put a listener every time input change to get the actual value from it if you wanna declare it on global scope. If you put height and weight into bmiCalc() it's working because the function is called only when the button is pressed so it takes the actual values from inputs (the current value when the button is pressed).如果您想在全局 scope 上声明它,则每次输入更改时都需要放置一个侦听器以从中获取实际值。如果将身高和体重放入 bmiCalc() 它正在工作,因为仅当按下按钮时才会调用 function 所以它从输入中获取实际值(按下按钮时的当前值)。

It's simply because the values for height and weight are being set the moment the page finishes loading, and before the bmiCalc function is even defined, bound, and run.这仅仅是因为heightweight的值是在页面完成加载时设置的,甚至在bmiCalc function 被定义、绑定和运行之前。 Since you would want to pull fresh values when you click the calculate button, you need to have the code that reads the fields inside the bmiCalc function, otherwise, you'll only get the values that were there on startup.由于您希望在单击计算按钮时提取新值,因此您需要具有读取bmiCalc function 内字段的代码,否则,您将只能获得启动时的值。 So, the variables are able to be accessed, but they're empty because there was nothing to read.因此,可以访问变量,但它们是空的,因为没有任何内容可读。

If you want to define element getters outside the function, you could rewrite it this way:如果你想在 function 之外定义元素 getter,你可以这样重写:


const heightInput = document.querySelector("#height");
const weightInput = document.querySelector("#weight");
const results = document.querySelector("#results");

function bmiCalc() {
  const height = parseInt(heightInput.value);
  const weight = parseInt(weightInput.value);
  if (height === "" || isNaN(height))
    results.innerHTML = "Invalid Height! Please use numbers";
  else if (weight === "" || isNaN(weight))
    results.innerHTML = "Invalid Weight! Please use numbers";
  else {
    const bmi = (weight / ((height * height) / 10000)).toFixed();
    results.innerHTML = bmi;
  }
}

const button = document.querySelector(".results__btn");

button.addEventListener("click", bmiCalc);

What this does differently is it binds the input elements outside of the function, but then actually reads and parses their contents inside the function when it's called.它的不同之处在于它绑定了 function 外部的输入元素,但随后在调用时实际读取并解析了 function 内部的内容。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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