所以,我想這樣做,如果由于某種原因,人們在我的計算器上輸入錯誤/錯誤點擊了某些內容,它會顯示語法錯誤。但是,我不知道該怎么做。
我所說的“錯誤輸入”是指某人可能不小心寫了以下內容:
10 / 10
當他們真正想寫 10 10 時。
目前,我的計算器只顯示出現錯誤時輸入的方程式,并沒有做任何其他事情。為了效率,我只想添加該功能。
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>
uj5u.com熱心網友回復:
您可以檢測到 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
}
然后要提醒用戶,您可以使用警報功能提醒用戶或在 div 中顯示文本,與設定結果的方式相同。有語法錯誤。
但是,我認為您的計算器存在一些基本問題。我認為從一開始就阻止用戶使用無效運算式會更合適。
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/373311.html
