javascript - 是否有解决“无效值”的方法?
问题描述
似乎我找不到为什么每次我输入一些东西时它都会显示。它应该只在用户输入字母或负数时显示。它与“其他”有关吗?
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Examus</title>
</head>
<body>
<h1 id="label"></h1>
<input type="text" id="input">
<button onclick="checkAge()">Check Age</button>
<script>
const checkAge = () => {
const input = document.getElementById("input");
const inputValue = parseInt(input.value);
let output;
if (Number.isInteger(inputValue) || inputValue < 0) {
output = "Invalid Value";
document.getElementById("label").innerText = output;
return;
}
if (inputValue < 14 && inputValue > 0) {
output = "This person is a KID";
} else if (inputValue > 14 && inputValue < 18) {
output = "This person is a TEEN";
} else if (inputValue > 18 && inputValue < 60) {
output = "This person is a ADULT";
} else if (inputValue > 60) {
output = "This person is a SENIOR";
} else {
output = "Invalid Value";
}
document.getElementById("label").innerText = output;
}
</script>
</body>
</html>
解决方案
我敢打赌你想说:如果它不是数字或小于零:
if( Number.isInteger(inputValue) || inputValue < 0 ) {
所以你需要在调用 Number.isInteger 之前添加布尔反转:
if( ! Number.isInteger(inputValue) || inputValue < 0 ) {
此外,您将需要使用运算符“小于或等于”(<=
)或“大于或等于”(>=
),因此您的条件将包括 14、18 和 60 岁:
if (!Number.isInteger(inputValue)) {
document.getElementById("label").innerText = "Invalid Value";
return;
}
if (inputValue >= 0 && inputValue < 14) {
output = "This person is a KID";
} else if (inputValue >= 14 && inputValue < 18) {
output = "This person is a TEEN";
} else if (inputValue >= 18 && inputValue < 60) {
output = "This person is a ADULT";
} else if (inputValue >= 60) {
output = "This person is a SENIOR";
} else {
output = "Invalid Value";
}
推荐阅读
- apache - Apache 作为反向代理和负载均衡器需要使用粘性会话
- vb.net - 在所需位置的 ImageBox 上绘图
- c - 超过4个参数的“snprintf”有什么用?
- java - 矩阵上的 Dijkstra 算法
- typescript - 如何使用打字稿模块扩充修补类构造函数?
- docker - Nginx 代理管理器(NGINX 反向代理)可以连接到 Cloudflare Argo 隧道吗?
- mongodb - Mongoose如何将元素推送到数组数组的模式
- c# - c# 将字符串解析为日期。'yyyyMMddHHmmss.ffffff+zzz'
- java - 值未存储在不同方法之间的变量中(初学者java项目)
- python - Docker如何将python 3.8设为默认