简单计算器
程序员文章站
2022-03-06 13:12:05
...
简单计算器
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input type="text" name="num1" id="num1" value="">
<select name="choice" id="choice">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
<option value="%">%</option>
</select>
<input type="text" name="num2" id="num2">
<input type="button" id="calc" value="计算">
<p id="res"></p>
<script>
document.getElementById('calc').onclick = function () {
var num1 = document.getElementById('num1').value
var num2 = document.getElementById('num2').value
var choice = document.getElementById('choice').value
var res = ''
if (num1 == '' || isNaN(num1 * 1)) res += '第一个输入框必须为数字'
if (num2 == '' || isNaN(num2 * 1)) res += '第二个输入框必须为数字'
if ((choice == '/' || choice == '%') && num2 * 1 == 0) res += '第二个输入框不能为零'
num1 = num1 * 1;
num2 = num2 * 1;
if (!res) {
switch (choice) {
case '+':
res = num1 + num2
break
case '-':
res = num1 - num2
break
case '*':
res = num1 * num2
break
case '/':
res = num1 / num2
break
default:
res = num1 % num2
}
}
document.getElementById('res').innerText = res
}
</script>
</body>
</html>
上一篇: 小鸟云虚拟主机和云服务器和裸金属服务器有何不一样?
下一篇: 古典的服饰怎么画?古典服饰参考画法!