繁体   English   中英

获取Javascript计算器,仅用2个数字输入即可完成类似(5-3 + 2)的方程式

[英]Get Javascript calculator to do an equation like (5-3+2) with only 2 number inputs

我正在制作此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>

您正在尝试将(转换为整数,但不能(因为不是):

function calc()
{
    var D = "";
    var A = document.getElementById("num1").value;
    var B = document.getElementById("op").value;
    var C = document.getElementById("num2").value;

    D = eval(A + B + C);


    document.getElementById("result").value = D;
}

暂无
暂无

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

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