js简单计算器和一个深坑
程序员文章站
2022-03-06 13:11:59
...
今天用js写了一个简单的计算器,别的都还好说,遇到一个最大的坑应该是input输入的数字拿到之后竟然为string类型,type=”number”也不行!坑坑坑!!!
上代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>计算器</title>
</head>
<body>
<input type="text" name="num1" id="num1" value="">
<select name="ys" id="ys">
<option value="+">+</option>
<option value="-">-</option>
<option value="*">*</option>
<option value="/">/</option>
<option value="%">%</option>
</select>
<input type="text" name="num2" id="num2" value="">
<button onclick="js()">计算</button>
<p id="res"></p>
<script>
function js() {
var res = '',
num1 = document.getElementById('num1').value,
num2 = document.getElementById('num2').value,
ysf = document.getElementById('ys').value,
resObj = document.getElementById('res');
console.log(num1);
console.log(typeof (num1));
if (num1.length < 1) {
res += 'num1不能为空!';
}
if (num2.length < 1) {
res += 'num2不能为空!'
}
num1 = parseFloat(num1);
num2 = parseFloat(num2);
if (isNaN(num1)) {
res += 'num1不能为非数字!';
}
if (isNaN(num2)) {
res += 'num2不能为非数字';
}
if (res.length == 0) {
switch (ysf) {
case '+':
res = num1 + num2;
break;
case '-':
res = num1 - num2;
break;
case '*':
res = num1 * num2;
break;
case '/':
if (num2 == 0) {
res += '除数不能为零!';
} else {
res = num1 / num2;
}
break;
case '%':
if (num2 == 0) {
res += '除数不能为零!';
} else {
res = num1 % num2;
}
break;
}
}
resObj.innerText = res
}
</script>
</body>
</html>
下一篇: 关于session