You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何为HTML/JavaScript/CSS计算器添加输入不合法时的Syntax Error报错功能

解决方案

你只需要给solve()函数增加try...catch异常捕获逻辑即可,eval()执行非法表达式时会抛出错误,捕获后直接在输入框展示语法错误提示就行。同时我也顺便修正了你原HTML代码里的两处小问题:

  • 标题div的class属性写错成t itle,修正为title
  • 第二行按键的末尾多了一个冗余的</td>标签,已经删除

修改后的完整JS代码

function dis(val) {
  document.getElementById("result").value += val
}

function solve() {
  let x = document.getElementById("result").value
  try {
    let y = eval(x)
    document.getElementById("result").value = y
  } catch (err) {
    // 捕获所有执行异常,统一显示语法错误提示
    document.getElementById("result").value = "Syntax Error"
  }
}

function clr() {
  document.getElementById("result").value = ""
}

修正后的HTML代码(可选,修复原有排版问题)

<div class="title">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('&nbsp;/&nbsp;')" /> </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>
  </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('&nbsp;+&nbsp;')" /> </td>
    <td><input type="button" value="-" onclick="dis('&nbsp;-&nbsp;')" />
  </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('&nbsp*&nbsp;')" /> </td>
    <td><input type="button" value="π" onclick="dis('3.1415926535')"></td>
  </tr>
</table>

效果说明

修改完成后,用户输入非法表达式点击等号时,输入框会直接显示Syntax Error提示,点击清除按钮即可重置输入重新使用。

内容的提问来源于stack exchange,提问作者A Random Beginner Coder

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.23 16:06:04