我希望你很好!!
最近我按照youtube上的教程创建了这个计算器。 你怎么看下面我把所有变量都放在函数之外。 在Firefox工作正常,但如果我使用谷歌Chrome,我尝试使用它,给我NaN的结果.....我修复了这个错误移动函数内部的var,但我不明白为什么用Chrome我必须把它移到里面而Firefox没有......
如果有人能够给我解释,我将非常感激!
感谢!!!!
var value1 = parseInt(document.querySelector("#textbox1").value);
var value2 = parseInt(document.querySelector("#textbox2").value);
var operator = document.querySelector("#operators").value;
var total = document.getElementById("total");
var calculate;
function result() {
if (operator === "add") {
calculate = value1 + value2;
} else if (operator === "sub") {
calculate = value1 - value2;
} else if (operator === "multiply") {
calculate = value1 * value2;
} else if (operator === "divide") {
calculate = value1 / value2;
}
total.innerHTML = calculate;
}
<form>
<input type="text" id="textbox1">
<input type="text" id="textbox2"><br>
<select id="operators">
<option value="add">Add</option>
<option value="sub">Sub</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="button" id="confirm" value="Result" onclick="result()">
<div id="total"></div>
</form>
答案 0 :(得分:2)
问题是,当用户在页面加载时立即填写之前,会抓取值。 (你已经说过它在Firefox中“正常工作”。它不适合我,但是如果你启用了自动填充功能,它可能会填充之前运行的值。)
相反,请抓取 result
函数中的值:
var total = document.getElementById("total");
function result() {
var value1 = parseInt(document.querySelector("#textbox1").value);
var value2 = parseInt(document.querySelector("#textbox2").value);
var operator = document.querySelector("#operators").value;
var calculate;
if (operator === "add") {
calculate = value1 + value2;
} else if (operator === "sub") {
calculate = value1 - value2;
} else if (operator === "multiply") {
calculate = value1 * value2;
} else if (operator === "divide") {
calculate = value1 / value2;
}
total.innerHTML = calculate;
}
<form>
<input type="text" id="textbox1">
<input type="text" id="textbox2"><br>
<select id="operators">
<option value="add">Add</option>
<option value="sub">Sub</option>
<option value="multiply">Multiply</option>
<option value="divide">Divide</option>
</select>
<input type="button" id="confirm" value="Result" onclick="result()">
<div id="total"></div>
</form>