首页 > 解决方案 > 是否有解决“无效值”的方法?

问题描述

似乎我找不到为什么每次我输入一些东西时它都会显示。它应该只在用户输入字母或负数时显示。它与“其他”有关吗?

<!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>

标签: javascripthtmlif-statementinputuser-input

解决方案


我敢打赌你想说:如果它不是数字或小于零:

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";
}

推荐阅读