<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" id="number1">
<select id="selector">
<option selected>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
<input type="text" id="number2">
=
<span id="result"></span>
<input type="button" onclick="calc()" value="计算">
<script>
function calc(){
//获取编辑框1.内容
let num1 = document.getElementById("number1").value;
//判断是否为空
if(num1===""){alert("请输入第一个数");return ;}
//判断是否为数字
if(isNaN(num1)){alert("请在第一个输入框输入一个数字");return ;}
//获取编辑框2.内容
let num2 = document.getElementById("number2").value;
if(num2===""){alert("请输入第二个数");return ;}
if(isNaN(num2)){alert("请在第二个输入框输入一个数字");return ;}
//获取运算符号
let t = document.getElementById("selector").value;
//获取第三个编辑框以便计算后显示运算结果
let result = document.getElementById("result");
//将字符串转为数字
try{
num1 = parseFloat(num1)
num2 = parseFloat(num2)
}catch (err){
alert(err.message)
return ;
}
//当做除法时,除数不能为0
if(t==="/" && num2===0) {
alert("除数不能为0")
return;
}
//根据运算符选择相应的计算
switch (t){
case '+':
result.innerText = (num1+num2).toString();
break;
case '-':
result.innerText = (num1-num2).toString();
break;
case '*':
result.innerText = (num1 * num2).toString();
break;
case '/':
result.innerText = (num1 / num2).toString();
break;
default:
result.innerText = "what happen?"
}
return result.innerText;
}
</script>
</body>
</html>
标签:return,num1,num2,JavaScript,alert,innerText,result,计算器,加减乘除
From: https://www.cnblogs.com/mllt/p/web_javascript_jjcc.html