JavaScript Calculator Tutorial: Create Web Calculator
JavaScript can be used to implement the functionality of a web calculator, here is a simple example:
<!DOCTYPE html>
<html>
<head>
<title>网页计算器</title>
</head>
<body>
<h1>网页计算器</h1>
<input type="text" id="input" readonly>
<br>
<button onclick="clearInput()">C</button>
<button onclick="appendInput('+')">+</button>
<button onclick="appendInput('-">-</button>
<button onclick="appendInput('*">*</button>
<button onclick="appendInput('/')">/</button>
<br>
<button onclick="appendInput('7')">7</button>
<button onclick="appendInput('8')">8</button>
<button onclick="appendInput('9')">9</button>
<button onclick="calculate()">=</button>
<br>
<button onclick="appendInput('4')">4</button>
<button onclick="appendInput('5')">5</button>
<button onclick="appendInput('6')">6</button>
<button onclick="appendInput('('">(</button>
<button onclick="appendInput(')')">)</button>
<br>
<button onclick="appendInput('1')">1</button>
<button onclick="appendInput('2')">2</button>
<button onclick="appendInput('3')">3</button>
<button onclick="appendInput('.')">.</button>
<br>
<button onclick="appendInput('0')">0</button>
<script>
function appendInput(value) {
document.getElementById('input').value += value;
}
function calculate() {
let expression = document.getElementById('input').value;
try {
let result = eval(expression);
document.getElementById('input').value = result;
} catch (error) {
alert('输入表达式无效,请重新输入');
}
}
function clearInput() {
document.getElementById('input').value = '';
}
</script>
</body>
</html>
In this example, we have created a basic web calculator where users can input expressions in a box and then click the “=” button to calculate. The calculator supports basic operations like addition, subtraction, multiplication, and division, and also features a clear button to erase the input. The result of the expression is evaluated using JavaScript’s eval function. If the input expression is invalid, a prompt will appear asking the user to re-enter the expression.