我的console.log一直说NaN是假的,但它不是

时间:2016-06-04 22:11:22

标签: javascript html nan

所以我有这个代码,当用户键入一个数字时,它应该记录"这是一个有效的数字"在控制台中,它应该记录"这不是一个有效的数字"。但我的代码一直在记录"这是一个有效的数字"。我必须使用isNaN。

请放轻松,我刚开始使用JavaScript。

这是我的HTML代码:

  <!doctype html>
<html>

<head>
    <meta charset="UTF-8">
    <title>Postcode</title>


    <script src="postcode.js">
 </script>
</head>

<body>

<form class="form">
  <label for="postcode">Postcode: </label>
  <input type="text" id="postcode">
</form>

</body>

</html>

这是我的JavaScript代码:

window.addEventListener("load", init);

  function init() {
    alert("Content loaded");

    var nameInput = document.getElementById('postcode');

    document.querySelector('form.form').addEventListener('submit', function (e) {

      //prevent the normal submission of the form
      e.preventDefault();



        if (nameInput === isNaN || nameInput === "") {
          console.log("this is not a valid number!");}
        else if (nameInput !==  isNaN) {
          console.log("this is a valid number!");}

    });

    }

3 个答案:

答案 0 :(得分:2)

javascript中有一些名为NaN (非数字)的内容,然后有一个函数可以检查NaN是否恰当地称为isNaN()

您正在检查您的变量是否与isNaN函数完全相同,当然它不是,因为nameInput是一个对象,或者更正确的是HTML输入元素。

你想要的是获取输入的值,并检查它是否为“Not A Number”,或者只是一个空字符串(这似乎是一个不必要的检查)

if (isNaN(nameInput.value) || nameInput.value === "") {

答案 1 :(得分:1)

使用isNaN(...)检查某件事是否不是数字:

isNaN('a'); // true

并且nameInput也指DOM节点,获取值(或innerHTML):

isNaN(nameInput.value)

您的完整代码:

window.addEventListener("load", init);

function init() {
    var nameInput = document.getElementById('postcode');
    document.querySelector('.form').addEventListener('submit', function (e) {
        e.preventDefault();
        if (!nameInput.value || isNaN(nameInput.value)) {
            console.log("this is not a valid number!");}
        else {
            console.log("this is a valid number!");}
        }
    });
}

答案 2 :(得分:0)

isNaN是一个函数。如果您执行nameInput === isNaN,则会检查nameInput是否指向函数isNaN。 你想要做的是调用函数:isNaN(nameInput)

nameInput也是HTML DOM Element。您首先必须从中获取值:nameInput.value

只是做:

if (isNaN(nameInput.value)) {
    console.log("this is not a valid number!");}
else {
    console.log("this is a valid number!");
}
相关问题