isNan函数的问题

时间:2017-03-26 11:30:10

标签: javascript

我有一个文本框和按钮,用户必须在1到10之间输入一个标记。这样的内部HTML显示标记为百分比。

让我的isNaN函数在我的代码中使用超过10的数字或者确实不是数字的值时,我有点困难。

除了这个特定部分,代码效果很好,我想知道我哪里出错了。

<script>

    function myFunction() {

        var x, text;

        // Get the value of the input field with id="numb"
        x = document.getElementById("numb").value;

        // If x is Not a Number or less than one or greater than 10
        if (isNaN(x) || x < 1 || x > 10) {
            text = "Input not valid";
        } else  {
            text = "Your final mark is";
        }



        document.getElementById("demo").innerHTML = (x) * 10 + "%";
    }

    </script>



<body>

    <h1>JavaScript to Validate Input</h1>

    <p>Enter your mark between 1 and 10:</p>

    <input id="numb">

    <button type="button" onclick="myFunction()">Submit</button>

    <p id="demo"></p>




</body>

2 个答案:

答案 0 :(得分:3)

您的if - else逻辑工作正常(假设您首先使用一元x运算符将字符串+强制转换为数字);问题是你没有对你的text变量做任何事情。您应该只在输入有效时将百分比添加到text,如下所示:

function myFunction() {

  var text

  var x = +document.getElementById("numb").value

  if (isNaN(x) || x < 1 || x > 10) {
    text = "Input not valid"
  } else {
    text = "Your final mark is: " + (x * 10) + "%"
  }

  document.getElementById("demo").textContent = text
}
<body>
  <h1>JavaScript to Validate Input</h1>
  <p>Enter your mark between 1 and 10:</p>
  <input id="numb">
  <button type="button" onclick="myFunction()">Submit</button>
  <p id="demo"></p>
</body>

答案 1 :(得分:0)

您应该将document.getElementById("demo").innerHTML = (x) * 10 + "%";放在else

function myFunction() {

        var x, text;

        // Get the value of the input field with id="numb"
        x = document.getElementById("numb").value;

        // If x is Not a Number or less than one or greater than 10
        if (isNaN(x) || x < 1 || x > 10) {
            text = "Input not valid";
        } else  {
           document.getElementById("demo").innerHTML = (x) * 10 + "%";
            text = "Your final mark is";
        }
        console.log(text);



        
    }
<body>

    <h1>JavaScript to Validate Input</h1>

    <p>Enter your mark between 1 and 10:</p>

    <input id="numb">

    <button type="button" onclick="myFunction()">Submit</button>

    <p id="demo"></p>




</body>