我正在制作这个 Javascript 计算器,但我不知道如何让计算器解决 5-(3+1)、5-3+1 之类的问题。它只打印等式的 5-3 部分而不是 +1 这是我的代码:
<html>
<script>
function calc()
{
var D = "";
var A = document.getElementById("num1").value;
var B = document.getElementById("op").value;
var C = parseInt(document.getElementById("num2").value);
if(B == "+")
{
D = parseInt(A)+parseInt(C);
}
else if(B == "-")
{
D = parseInt(A)-parseInt(C);
}
else if(B == "*")
{
D = parseInt(A)*parseInt(C);
}
else if(B == "/")
{
D = parseInt(A)/parseInt(C);
}
else
{
alert("Error")
}
document.getElementById("result").value = parseInt(D);
}
function conteq()
{
var D = document.getElementById("result").value;
var E = "";
document.getElementById("num1").value = D;
document.getElementById("op").value = E;
document.getElementById("num2").value = E;
document.getElementById("result").value = E;
}
function resetcalc()
{
var E = "";
document.getElementById("num1").value = E;
document.getElementById("op").value = E;
document.getElementById("num2").value = E;
document.getElementById("result").value = E;
}
</script>
<body>
<table align="center">
<td>This is a basic Javascript Calculator.<br /></td></table>
<table align="center"><td>(Number 1)<input type="text" id="num1" align="middle" name="num1" />
</td>
<table align="center"><td>(Operator)<input type="text" align="middle" id="op" name="op" /></td> </table>
<table align="center"> <td>(Number 2)<input type="text" align="middle" id="num2" name="num2" /></td> </table>
<table align="center"> <td><input type="button" align="middle" value="=" onClick="calc()" /></td> </table>
<table align="center"><td>(Result)<input type="text" id="result" name="result" readonly />
</td></table>
<table align="center"><td><input type="button" value="Set Answer to Number 1" onClick="conteq()" /></td></table>
<table align="center"><td><input type="button" value="Reset" onClick="resetcalc()" /></td></table>
</table>
</p>
</body>
</html>