当我尝试比较不同的数字时,数字会发生变化,但文本部分保持不变。这只发生在更大/更小的情况下,而不是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>
答案 0 :(得分:1)
值a
和b
都是字符串。如果您想将它们与数字进行比较,请在执行比较之前使用parseInt()
或parseFloat()
。
所以,在if语句之前:
a = parseInt(a);
b = parseInt(b);