[英]How do I add "Syntax Error" if the numbers aren't compatible on my html/javascript/css calculator?
所以,我想这样做,如果由于某种原因,人们在我的计算器上输入错误/点击错误,它会显示语法错误。 但是,我不知道该怎么做。
我所说的“输入错误”是指有人可能不小心写了如下内容:
10 + / 10
当他们实际上想写 10 + 10 时。
目前,我的计算器只显示出现错误时输入的公式,不做任何其他事情。 为了提高效率,我只想添加 function。
function dis(val) { document.getElementById("result").value += val } function solve() { let x = document.getElementById("result").value let y = eval(x) document.getElementById("result").value = y } function clr() { document.getElementById("result").value = " " }
.title { margin-bottom: 10px; text-align: center; width: 100%; color: Black; border: solid gray 2px; font-size: 30px } input[type="button"] { background-color: gray; color: black; border: solid black 2px; width: 100%; font-size: 30px } input[type="button"]:hover { background-color: #D3D3D3; cursor: pointer; } input[type="text"] { background-color: white; border: solid black 2px; width: 100%; font-size: 30px }
<div class=t itle>Calculator</div> <table border="10" style="width:100%;"> <tr> <td colspan="3"><input type="text" id="result" /></td> </tr> <tr> <td><input type="button" value="1" onclick="dis('1')" /> </td> <td><input type="button" value="2" onclick="dis('2')" /> </td> <td><input type="button" value="3" onclick="dis('3')" /> </td> <td><input type="button" value="/" onclick="dis(' / ')" /> </td> <td><input type="button" value="c" onclick="clr()" /> </td> </tr> <tr> <td><input type="button" value="4" onclick="dis('4')" /> </td> <td><input type="button" value="5" onclick="dis('5')" /> </td> <td><input type="button" value="6" onclick="dis('6')" /> </td> <td><input type="button" value="(" onclick="dis('(')" /> </td> <td><input type="button" value=")" onclick="dis(')')" /> </td> </td> </tr> <tr> <td><input type="button" value="7" onclick="dis('7')" /> </td> <td><input type="button" value="8" onclick="dis('8')" /> </td> <td><input type="button" value="9" onclick="dis('9')" /> </td> <td><input type="button" value="+" onclick="dis(' + ')" /> </td> <td><input type="button" value="-" onclick="dis(' - ')" /> </tr> <tr> <td><input type="button" value="." onclick="dis('.')" /> </td> <td><input type="button" value="0" onclick="dis('0')" /> </td> <td><input type="button" value="=" onclick="solve()" /> </td> <td><input type="button" value="×" onclick="dis(' * ')" /> </td> <td><input type="button" value="π" onclick="dis('3.1415926535')"></td> </tr> </table>
您可以检测到 REGEX 存在语法错误,例如检测无效的数学表达式。 您还可以将eval
包装在 try catch 块中,因为无效的表达式会引发错误。
使用 try/catch 的示例
function solve()
{
let x = document.getElementById("result").value
let y;
try {
y = eval(x)
} catch (error) {
alert("Syntax error");
return;
}
document.getElementById("result").value = y
}
然后要提醒用户,您可以使用 警报 function提醒用户或在 div 中显示文本,与设置结果的方式相同。 存在语法错误。
但是我认为您的计算器存在一些基本问题。 我认为从一开始就阻止用户做出无效的表达会更合适。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.