如何比较JavaScript表单中的两个数字?

内容来源于 Stack Overflow,并遵循CC BY-SA 3.0许可协议进行翻译与使用

  • 回答 (1)
  • 关注 (0)
  • 查看 (63)

当我试图比较不同的数字时,数字会改变,但文本部分保持不变。这种情况只发生在较大/较少的情况下,而不是在NaN或相同情况下发生。

我的代码:

function check() {
    var a = document.getElementById("a").value;
    var b = document.getElementById("b").value;
    
    if (isNaN(a) || isNaN(b) === true) {
        document.getElementById("result").innerHTML = "It's not a number";
    } else {
        if (a > b) {
            document.getElementById("result").innerHTML = "Number " + a + " is greater than number " + b;
        } else if (a == b) {
            document.getElementById("result").innerHTML = "number " + a + " is equal to number " + b;
        } else if (a < b) {
            document.getElementById("result").innerHTML = "number " + a + " is lesser than  number " + b;
        }
    }
}
body {
    background-color: black;
    color: white;
    font-size: 28px;
}
<!DOCTYPE HTML>
<html lang="pl">
    
<head>
    <meta charset="utf-8">
    <title>Check the value of a number compared to the second number</title>
    <script type="text/javascript" src="sprawdzanie.js"></script>
    <link href="style.css" rel="stylesheet">
</head>

<body>

    <input id="a" type="text">
    <input id="b" type="text">
    <input value="Check" type="submit" onclick="check()">
    


    <div id="result"></div>

</body>
    
    
</html>

提问于
用户回答回答于

扫码关注云+社区

领取腾讯云代金券