编写一个计算器函数,允许计算加减乘除。在网页上编写两个数字输入框,一个运算符选择框,点击计算按钮时,将运算结果放在第3个数字框。要求:两个运算数任意一个不是数字时都弹出警告框,除法运算时除数不能为0,如果除数为0则弹出警告框提示。(考点:函数的定义、函数调用、isNaN、弹出框、if分支语句)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
width: 453px;
height: 351px;
background: #e4f0e3;
margin: 10px auto;
text-align: center;
box-sizing: border-box;
padding-top: 10px;
padding-right: 50px;
}
.box h1 {
margin-bottom: 20px;
}
.box input,
button {
width: 297px;
height: 40px;
border: 2px solid #999;
margin: 4px 0px;
margin-left: 10px;
outline: none;
box-sizing: border-box;
}
button {
background: #00aa00;
color: #fff;
}
form {
text-align: right;
}
</style>
</head>
<body>
<div class="box">
<h1>计算器</h1>
<form action="#">
<p>
数1: <input type="text" id="num1">
</p>
<p>
数2: <input type="text" id="num2">
</p>
<select id="select">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
</select>
<button type="button" id="btn">计算</button>
<p>
结果: <input type="text" id="result">
</p>
</form>
</div>
<script>
/*
2. 拓展题:编写一个计算器函数,允许计算加减乘除。在网页上编写两个数字输入框,一个运算符选择框,点击计算按钮时,将运算结果放在第3个数字框。要求:两个运算数任意一个不是数字时都弹出警告框,除法运算时除数不能为0,如果除数为0则弹出警告框提示。(考点:函数的定义、函数调用、isNaN、弹出框、if分支语句) */
let n1, n2, sum;
btn.onclick = function () {
n1 = Number(num1.value);
n2 = Number(num2.value);
// isNaN:判断是文字(不是数字)就是ture
if (isNaN(n1) || isNaN(n2)) {//不是数字
alert("输入的不是数字");
};
// 判断空字符串
if (num1.value == "" || num2.value == "") {
alert("请输入值");
return "";
}
result.value = getPan(select.value);
}
function getPan(flag) {
if (flag == "+") {
sum = n1 + n2;
} else if (flag == "-") {
sum = n1 - n2;
} else if (flag == "*") {
sum = n1 * n2;
} else if (flag == "/") {
n2 == 0 ? alert("除数为0") : sum = n1 / n2;
}
return sum;
}
</script>
</body>
</html>