用Javascript编写一个简单计算器
时间: 2023-09-15 19:15:11 浏览: 88
好的,我可以为您提供一个基本的Javascript计算器代码:
HTML代码:
```
<!doctype html>
<html>
<head>
<title>JavaScript Calculator</title>
</head>
<body>
<h2>JavaScript Calculator</h2>
<form name="calculator">
<input type="text" name="answer" size="16">
<br><br>
<input type="button" value="1" onclick="calculator.answer.value+='1'">
<input type="button" value="2" onclick="calculator.answer.value+='2'">
<input type="button" value="3" onclick="calculator.answer.value+='3'">
<input type="button" value="+" onclick="calculator.answer.value+='+'">
<br><br>
<input type="button" value="4" onclick="calculator.answer.value+='4'">
<input type="button" value="5" onclick="calculator.answer.value+='5'">
<input type="button" value="6" onclick="calculator.answer.value+='6'">
<input type="button" value="-" onclick="calculator.answer.value+='-'">
<br><br>
<input type="button" value="7" onclick="calculator.answer.value+='7'">
<input type="button" value="8" onclick="calculator.answer.value+='8'">
<input type="button" value="9" onclick="calculator.answer.value+='9'">
<input type="button" value="*" onclick="calculator.answer.value+='*'">
<br><br>
<input type="button" value="C" onclick="calculator.answer.value=''">
<input type="button" value="0" onclick="calculator.answer.value+='0'">
<input type="button" value="=" onclick="calculator.answer.value=eval(calculator.answer.value)">
<input type="button" value="/" onclick="calculator.answer.value+='/'">
</form>
</body>
</html>
```
这段代码将生成一个简单的HTML页面,包含一个输入框和一组按钮,用于执行各种算术操作。当用户按下相应的按钮时,Javascript代码将将相应的数字或运算符添加到输入框中,并在用户单击“=”按钮时计算表达式并显示结果。
阅读全文