我需要制作一种带有按钮的“计算器”,其值为 1 到 10。然后,例如,当我按下“1”时,结果框将显示“1”,然后当我按下“4”时,结果将自动打印“5”,而无需按“=”按钮。
我只需要它来将值相加,并具有重置功能。
Javascript对我来说很新。我还不太擅长写它,但我几乎什么都懂。
真的希望有人能帮助我!
这是我当前的代码:
<html>
<head>
<style type="text/css">
table.calc {
border: 2px solid #0034D1;
background-color: #809FFF;
}
input.calc {
width: 100%;
margin: 5px;
}
</style>
<script>
function pushButton(buttonValue) {
if (buttonValue == 'C') {
document.getElementById('screen').value = '';
}
else {
document.getElementById('screen').value += buttonValue;
}
}
function calculate(equation) {
var answer = eval(equation);
document.getElementById('screen').value = answer;
}
</script>
</head>
<body>
<table class="calc" cellpadding=4>
<tr><td colspan=3><input class="calc" id="screen" type="text"></td></tr>
<tr>
<td><input class="calc" type="button" value=1 onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value=2 onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value=3 onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td><input class="calc" type="button" value=4 onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value=5 onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value=6 onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td><input class="calc" type="button" value=7 onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value=8 onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value=9 onclick="pushButton(this.value);"></td>
</tr>
<tr>
<td><input class="calc" type="button" value=0 onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value='.' onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value='C' onclick="pushButton(this.value);"></td>
<td><input class="calc" type="button" value='+' onclick="pushButton(this.value);"></td>
</tr>
<tr><td colspan=3><input class="calc" type="button" value='=' onclick="calculate(document.getElementById('screen').value);"></td></tr>
</table>
</body>
</html>