简体   繁体   English

设置全局变量并在函数中使用它们(javascript)

[英]Set a global variables and use them in function (javascript)

I am new to programming and I am stuck. 我是编程的新手,我被卡住了。 Here is my code: 这是我的代码:

function Subtraction() {
  var a = document.getElementById('inputA').value;
  var b = document.getElementById('inputB').value;
  var c = (parseFloat(a) - parseFloat(b)).toFixed(5);
  alert(c);
}

This works fine to me, but I have many functions that waits for onclick event to be executed. 这对我很好,但我有很多函数等待onclick事件执行。 And every function have the same a and b variables. 并且每个函数都有相同的ab变量。 How can I get them in global scope so I don't need to wait them over and over again? 我怎样才能将它们放到全球范围内,所以我不需要一遍又一遍地等待它们? I tried to put them outside of the function, but what event can trigger their declaration? 我试图将它们放在函数之外,但是什么事件可以触发它们的声明? There is what I tried: 有我尝试过的:

var a = document.getElementById('inputA').value;
var b = document.getElementById('inputB').value;
parseFloat(a).toFixed(5);
parseFloat(b).toFixed(5);
function Subtraction() {
  var c = a - b;
  alert(c);
}

I see two options at least: 我至少看到两个选项:

One is to declare them after window has loaded. 一种是在窗口加载后声明它们。 Other is to pass the elements as function parameters: 其他是将元素作为函数参数传递:

1 1

var a,b;
window.onload = function(){
    a = document.getElementById('inputA').value;
    b = document.getElementById('inputB').value;
}

2 2

element.onclick = function(){
    var a = document.getElementById('inputA').value;
    var b = document.getElementById('inputB').value;
    Subtraction(a, b);
};

Btw, capital letters is used for Classes, if its a normal function better to use small "s". 顺便说一句,大写字母用于类,如果它的正常函数更好地使用小“s”。

You can try to declare the vars in a different javascript source file or put them in an upper block the environment of the variables holds through the entire execution from the moment you declare them so if you do this: 您可以尝试在不同的javascript源文件中声明变量,或者将它们放在上面的块中,变量的环境从您声明它们的那一刻起贯穿整个执行,如果您这样做:

<script src="declare_vars.js"></script>
<script src="use_vars.js"></script>

In declare_vars.js you can try doing: 在declare_vars.js中,您可以尝试:

var a;
var b;

and in the other scripts use them as you want and give them the values you need, they will always be available. 在其他脚本中根据需要使用它们并为它们提供所需的值,它们将始终可用。

The value of an input is a primitive (specifically a string) and is therefore passed by value. 输入的值是基元(特别是字符串),因此按值传递。 This means that if you do this: 这意味着如果你这样做:

var oldvalue = document.getElementById('someinput').value;
document.getElementById('someinput').value = "derp";
alert(oldvalue); // it has not changed

What you can do, if you want, is cache the result of getElementById : 如果需要,您可以执行的操作是缓存getElementById的结果:

var inputA = document.getElementById('inputA');
var inputB = document.getElementById('inputB');
// in your function {
    var c = parseFloat(inputA.value)-parseFloat(inputB.value);
// }

This works because the result of getElementById is the input element itself. 这是有效的,因为getElementById的结果是输入元素本身。 You then retrieve the desired property of this element ( .value ) at the specific time you need it. 然后,在您需要的特定时间检索此元素( .value )的所需属性。

That said, avoid global variables. 也就是说,避免全局变量。 Put variables in a scope if you want, but don't make them global. 如果需要,可以将变量放在作用域中,但不要将它们设置为全局变量。

Disclaimer: this solution makes no attempt to avoid using global variables. 免责声明:此解决方案不会尝试避免使用全局变量。 The usage of global variables may introduce all sorts of problems, though for an application as simple as the one described by the OP the potential pitfalls are limited. 全局变量的使用可能会引入各种问题,但是对于像OP所描述的那样简单的应用程序,潜在的缺陷是有限的。


You can add the initialization in the change event handler of each input to make sure it is always up to date: 您可以在每个输入的change事件处理程序中添加初始化,以确保它始终是最新的:

HTML HTML

  a<input id="inputA"/>
  b<input id="inputB"/>
  <button id="sum">sum</button>

JAVASCRIPT JAVASCRIPT

var a,b;

document.getElementById('inputA').addEventListener('change',function(evt){
  a = +evt.target.value;
});

document.getElementById('inputB').addEventListener('change',function(evt){
  b = +evt.target.value;
});

document.getElementById('sum').addEventListener('click', function(evt){
  console.log('Sum is ' + (a+b));
});

DEMO: http://jsbin.com/EZECEraR/2/edit 演示: http//jsbin.com/EZECEraR/2/edit

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

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