我试图检查文本框中键入的击键是否为数字。无论我输入的是什么,都会给我提供相同的警报窗口。它说"你输入的数字不是数字"。我似乎无法找到它为什么这样做。
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Part 1</title>
<script>
function Numcheck(){
var number = Number(document.getElementById("enteredChar").value)
try{
if ("number" == "") throw "was empty"
if (isNaN("number")) throw "is not a number"
if (isFinite("number")) throw "is good."
}
catch(err){
alert("The number you entered " + err);
}
}
</script>
</head>
<body>
<form action="">
<input type="text" id="enteredChar" onkeypress="Numcheck()"/>
</form>
</body>
</html>
答案 0 :(得分:4)
if (isNaN("number")) throw "is not a number"
您传入isNaN
函数的值是"number"
,实际上是字符串而不是数字。
您应该将所有"number"
更改为number
,这是变量的名称。
示例:
<script>
function Numcheck() {
var number = Number(document.getElementById("enteredChar").value)
try {
//This if is not required. number will never be an empty string.
//It will be either a valid number, or NaN.
//if (number == "") throw "was empty";
if (isNaN(number)) throw "is not a number";
if (isFinite(number)) throw "is good.";
}
catch(err) {
alert("The number you entered " + err);
}
}
</script>