当我将所有变量(box2
、display
、total
、error
)放在函数中时,代码可以工作,但当我将它们放在函数外时,它不起作用。我想它应该有效,因为所有这 4 个变量都是全局变量,函数必须识别它们(变量)。如果有人能出来解释为什么代码不起作用,我会很高兴。
var box1 = document.getElementById("box1").value;
var box2 = document.getElementById("box2").value;
var display = document.getElementById("display");
var total = Number(box1) + Number(box2);
var error = "There is a problem with the input fields";
function cal() {
if (!isNaN(box1) && !isNaN(box2)) {
display.innerHTML = "$" + total;
} else {
display.innerHTML = error;
}
}
<h1>Best Addiction Calculator</h1>
<input class="field" placeholder="type first number" type="text" id="box1">
<input class="field" placeholder="type second number" type="text" id="box2">
<button style="font-size:xx-large; color:#860EED" onClick="cal()">Calculate</button>
<p id="display">i</p>
提前谢谢大家!
问题不在于变量在哪里,而在于您设置它们的值时。
此代码:
var box1 = document.getElementById("box1").value;
var box2 = document.getElementById("box2").value;
在运行时从输入中读取值。您希望在用户单击按钮时读取其值。
你可以这样做,但这是不合理的:
// JUST AN EXAMPLE, DON'T ACTUALLY DO IT
var box1;
var box2;
var display;
var total;
var error;
function cal() {
box1 = document.getElementById("box1").value;
box2 = document.getElementById("box2").value;
display = document.getElementById("display");
total = Number(box1) + Number(box2);
error = "There is a problem with the input fields";
if (!isNaN(box1) && !isNaN(box2)) {
display.innerHTML = "$" + total;
} else {
display.innerHTML = error;
}
}
这表明问题不在于变量在哪里,而在于您何时设置它们的值。
但是如果没有充分的理由,您不会这样做。由于没有理由将这些变量放在函数之外,因此请将它们放在函数中。通常,为变量提供它可以具有的最窄范围。
如果查找元素是一项昂贵的操作,您只想执行一次(它不是,getElementById
非常快),您可以查找元素一次,然后在cal
内获取它们的值:
var box1 = document.getElementById("box1"); // Note no `.value` here
var box2 = document.getElementById("box2"); // Or here
var display = document.getElementById("display");
function cal() {
var total = Number(box1.value) + Number(box2.value); // Note change on this line
var error = "There is a problem with the input fields";
if (!isNaN(box1) && !isNaN(box2)) {
display.innerHTML = "$" + total;
} else {
display.innerHTML = error;
}
}