isNaN 警报每次都会响应。即使值为数字

问题描述 投票:0回答:1

在我的代码中,我有一个 if 语句,使用

isNaN()
。它正在检查数字字段上的输入。如果输入
isNaN()
(不是数字),它应该抛出
alert()
现在,无论输入什么,它都会抛出该警报。你能帮忙吗?谢谢。这是我的代码:

const increaseValue = document.getElementById('positive');
const enter = document.getElementById('enter-value');

// input reception code

function useInput(){
    enter.addEventListener('click', function(){
        if(isNaN(increaseValue)){
            alert("Your input was not a number! Try again.");
        }
    })
}
useInput();
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="veiwport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="FinanceTool.css">
    <title>Finance_Tool</title>
</head>
<body>
    <main>
            <input type="number" id="positive" class="input" placeholder="Input financial increase." min="0"/>
            <button type="submit" id="enter-value">Enter</button>
    </main>
    <script src="FinanceTool.js"></script>
</body>
</html>

javascript html alert isnan
1个回答
0
投票

如果运行

console.log(increaseValue)
,您将看到
increaseValue
是 HTML 元素的实例。如果您需要检查输入的值是否为数字,您应该将检查更改为:

        if(isNaN(increaseValue.value)){
            alert("Your input was not a number! Try again.");
        }

示例:

const increaseValue = document.getElementById('positive');
const enter = document.getElementById('enter-value');

// input reception code

function useInput(){
    enter.addEventListener('click', function(){
        if(isNaN(increaseValue.value)){
            alert("Your input was not a number! Try again.");
        }
    })
}

useInput();
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta name="veiwport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="FinanceTool.css">
    <title>Finance_Tool</title>
</head>
<body>
    <main>
            <input type="number" id="positive" class="input" placeholder="Input financial increase." min="0"/>
            <button type="submit" id="enter-value">Enter</button>
    </main>
    <script src="FinanceTool.js"></script>
</body>
</html>

© www.soinside.com 2019 - 2024. All rights reserved.