Number.isNaN 不适用于输入验证
Number.isNaN not working for input validation
我有问题。
当用户在 input
中输入非数字的内容时,我想显示一条提示“您有问题”。
function function1() {
var x = document.getElementById("number1").value;
if (Number.isNaN(x)) {
alert("you have a problem");
}
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mohsen Yeganeh</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<input type="text" id="number1">
<button type="submit" onclick="function1()">click me</button>
</body>
</html>
但是,它不起作用。哪里出错了?
Number.isNaN()
checks whether the argument is NaN
,不是是否是数字
Number.isNaN(NaN) // true
Number.isNaN("Hello World!") // false, "Hello World!" != NaN
您应该改用 isNaN()
,它会检查参数是否为数字:
function function1() {
var x = document.getElementById("number1").value;
if (isNaN(x)) {
alert("you have a problem");
}
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mohsen Yeganeh</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<input type="text" id="number1">
<button type="submit" onclick="function1()">click me</button>
</body>
</html>
我有问题。
当用户在 input
中输入非数字的内容时,我想显示一条提示“您有问题”。
function function1() {
var x = document.getElementById("number1").value;
if (Number.isNaN(x)) {
alert("you have a problem");
}
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mohsen Yeganeh</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<input type="text" id="number1">
<button type="submit" onclick="function1()">click me</button>
</body>
</html>
但是,它不起作用。哪里出错了?
Number.isNaN()
checks whether the argument is NaN
,不是是否是数字
Number.isNaN(NaN) // true
Number.isNaN("Hello World!") // false, "Hello World!" != NaN
您应该改用 isNaN()
,它会检查参数是否为数字:
function function1() {
var x = document.getElementById("number1").value;
if (isNaN(x)) {
alert("you have a problem");
}
}
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Mohsen Yeganeh</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<input type="text" id="number1">
<button type="submit" onclick="function1()">click me</button>
</body>
</html>