Javascript/HTML计算器清除异常:按下‘c’或‘=’无法清除值
解决计算器的清除与等于按钮功能问题
我来帮你搞定这两个按钮的问题,顺便修复代码里的其他小bug:
首先看一下你的代码里的核心问题:
1. 清除按钮('c')无效的原因
你给清除按钮写的点击事件是calculator.display.value += ' '——这只是在现有内容后面加了个空格,完全不是清空输入框啊!正确的做法应该是把输入框的值设置为空字符串。
2. 等于按钮('=')的逻辑错误
现在的等于按钮是把计算结果追加到原有表达式后面(calculator.display.value += eval(...)),比如你输入1+1,点击等于后会变成1+12,这显然不对。我们应该用计算结果替换掉原来的表达式。
3. 还有个拼写错误
数字8的按钮里,你把calculator写成了claculator(少了一个u),这个按钮点击后会报错,根本没法正常输入8。
4. 表格布局的小问题
最后一行<tr>里有5个<td>,但前面的行都是4个,会导致表格布局错乱,我把清除按钮调整到单独的一行,让布局更合理。
修正后的完整代码:
<form name='calculator'> <table> <tr> <td colspan='4'> <input type='text' name='display' id='display' disabled> </td> </tr> <tr> <td><input type='button' name='one' value='1' onclick="calculator.display.value += '1'"></td> <td><input type='button' name='two' value='2' onclick="calculator.display.value += '2'"></td> <td><input type='button' name='three' value='3' onclick="calculator.display.value += '3'"></td> <td><input type='button' class='operator' name='plus' value='+' onclick="calculator.display.value += '+'"></td> </tr> <tr> <td><input type='button' name='four' value='4' onclick="calculator.display.value += '4'"></td> <td><input type='button' name='five' value='5' onclick="calculator.display.value += '5'"></td> <td><input type='button' name='six' value='6' onclick="calculator.display.value += '6'"></td> <td><input type='button' name='minus' value='-' onclick="calculator.display.value += '-'"></td> </tr> <tr> <td><input type='button' name='seven' value='7' onclick="calculator.display.value += '7'"></td> <td><input type='button' name='eight' value='8' onclick="calculator.display.value += '8'"></td> <td><input type='button' name='nine' value='9' onclick="calculator.display.value += '9'"></td> <td><input type='button' name='equals' value='=' onclick=" try { calculator.display.value = eval(calculator.display.value); } catch(e) { calculator.display.value = 'Error'; } "></td> </tr> <tr> <td colspan='4'> <input type='button' id='clear' name='clear' value='c' onclick="calculator.display.value = ''"> </td> </tr> </table> </form>
关键修改说明:
- 清除按钮:把
onclick改成calculator.display.value = '',直接清空输入框。 - 等于按钮:
- 用
calculator.display.value = eval(...)替换追加操作,直接显示计算结果。 - 加了
try...catch包裹,防止输入无效表达式时报错(比如输入1++2),会显示Error提示。
- 用
- 数字8按钮:修正了
claculator的拼写错误,改成正确的calculator。 - 表格布局:把清除按钮放到单独一行,用
colspan='4'占满整行,解决布局错乱问题。
这样修改后,清除按钮可以正常清空输入框,等于按钮也能正确计算并显示结果啦!
内容的提问来源于stack exchange,提问作者J D
相关产品推荐
相关产品推荐

