我正在制作一个基本计算器,我希望用户计算的每个结果都显示在div历史记录中。问题是,无论何时进行计算,结果都会在历史记录下显示几分之一秒,然后消失。我正在使用的功能如下:
function sum() {
getNumbers();
var sum = input1 + input2;
alert(sum);
document.getElementById("History").innerHTML += sum;
}
如果需要我的完整html / js代码:
var input1, input2
function getNumbers() {
input1 = Number(document.getElementById("imp1").value);
input2 = Number(document.getElementById("imp2").value);
}
function sum() {
getNumbers();
var sum = input1 + input2;
alert(sum);
document.getElementById("History").innerHTML += "<br>" + sum;
}
function diff() {
getNumbers();
var diff = input1 - input2;
alert(diff);
document.getElementById("History").innerHTML += "<br>" + diff;
}
function prod() {
getNumbers();
var prod = input1 * input2;
alert(prod);
document.getElementById("History").innerHTML += "<br>" + prod;
}
function quot() {
getNumbers();
var quot = input1 / input2;
alert(quot);
document.getElementById("History").innerHTML += "<br>" + quot;
}
<!DOCTYPE html>
<html lang="en">
<head>
<title>Calculator</title>
<link rel ="stylesheet" href="calculator.css" />
<script src ="calculator.js"></script>
<div id="calc">
<form name="calc_input">
<input type="text" id="imp1" />
<input type="text" id="imp2" />
<!-- buttons -->
<button onclick="sum()" id="add" value="sum">Add</button>
<button onclick="diff()" id="subtract" value="diff">Subtract</button>
<button onclick="prod()" id="multiply" value="prod">Multiply</button>
<button onclick="quot()" id="divide" value="quot">Divide</button>
</form>
</div>
<div id="History">
<p>
History:
</p>
</div>
</head>
</html>
答案 0 :(得分:0)
默认情况下,它可能与具有提交行为的按钮有关。当您点击它时,可能是提交表单并重新加载页面。尝试为每个按钮添加type="button"
。