介绍:
JavaScript 是一种广泛应用于网页开发的脚本语言,它具有灵活、动态和强大的特性。本文将演示如何使用 JavaScript 创建一个简单的计算器,并实现基本的加减乘除操作。
正文:
javascript
<!DOCTYPE html>
<html>
<head>
<title>简单计算器</title>
</head>
<body>
<h1>简单计算器</h1>
<input id="num1" type="number" placeholder="请输入第一个数字">
<input id="num2" type="number" placeholder="请输入第二个数字">
<br>
<button onclick="add()">加</button>
<button onclick="subtract()">减</button>
<button onclick="multiply()">乘</button>
<button onclick="divide()">除</button>
<br>
<p id="result">结果将显示在这里</p>
<script>
function add() {
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var result = num1 + num2;
document.getElementById("result").innerHTML = "结果:" + result;
}
function subtract() {
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var result = num1 - num2;
document.getElementById("result").innerHTML = "结果:" + result;
}
function multiply() {
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var result = num1 * num2;
document.getElementById("result").innerHTML = "结果:" + result;
}
function divide() {
var num1 = parseInt(document.getElementById("num1").value);
var num2 = parseInt(document.getElementById("num2").value);
var result = num1 / num2;
document.getElementById("result").innerHTML = "结果:" + result;
}
</script>
</body>
</html>
\