功能:实现简单的加减乘除
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<input type="text" name="" id="num1" value="">
<select name="" id="op">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<input type="text" name="" id="num2" value="">
<input type="button" value="计算" onclick="calc()">
<input type="text" name="" id="num3" value="">
</body>
</html>
<script>
function calc(){
let num1Obj = document.getElementById("num1");
let num1 = num1Obj.value;
console.log(num1);
let num2Obj = document.getElementById("num2");
let num2 = num2Obj.value;
console.log(num2);
if(num1 == "" || num2 == ""){
alert("数据不合法");
return;
}
if(window.isNaN(num1) || window.isNaN(num2)){
alert("数据不合法");
return;
}
let opObj = document.getElementById("op");
let op = opObj.value;
console.log(op);
let num3;
if(op == "+"){
num3 = window.parseInt(num1) + window.parseInt(num2);
}else if (op == "-"){
num3 = window.parseInt(num1) - window.parseInt(num2);
}else if (op == "*"){
num3 = window.parseInt(num1) * window.parseInt(num2);
}else{
num3 = window.parseInt(num1) / window.parseInt(num2);
}
let num3Obj = document.getElementById("num3");
num3Obj.value = num3;
}
</script>
页面展示:

结果演示:
1.

2.

3.


该代码段展示了一个HTML表单,用户可以输入两个数字并选择加、减、乘、除四种运算,点击按钮后,JavaScript函数`calc()`将执行相应的数学计算并将结果显示在页面上。函数首先验证输入的合法性,然后根据选择的运算符进行计算。
2125

被折叠的 条评论
为什么被折叠?



