Javascript 验证函数总是回复无效
Javascript validation function always replying invalid
我所做的一切都是正确的,但对于所有值,该函数仅显示 "Invalid"。有人可以告诉我问题出在哪里吗?
<html>
<head>
<script>
function alpha()
{
var x = document.getElementById('input1');
var y = x.value;
var z = isNaN(y);
if(z<1 || z>10){console.log("Invalid");} else {console.log("valid");}
}
</script>
</head>
<body>
<button id="but1" onmouseover="alpha()" style="background:blue;">Click Me</button>
<p id=para1> Hello! This is paragraph One! </p>
<input type=text id=input1 >
</body>
</html>
提前致谢,很抱歉提出愚蠢的问题!但是,我找不到代码哪里出错了!
isNaN
returns 一个布尔值,并将其与数字进行比较。您需要将 x
与您的范围进行比较。
if(z || x<1 || x>10)
这里是我将如何清理你的代码
function alpha(){
//name your variables something meaningful
var userInputField = document.getElementById('input1');
//using parse int tells yourself and future programmers you want an int
//it also gives you NaN if it's not a number so you don't have to check yourself
//the 10 is the radix you want to convert to
var userInputedValue = parseInt(x.value,10);
//check explicitly for NaN will save you some headaches
if(userInputedValue === NaN || userInputedValue<1 || userInputedValue>10){
console.log("Invalid");
} else {
console.log("valid");
}
}
我所做的一切都是正确的,但对于所有值,该函数仅显示 "Invalid"。有人可以告诉我问题出在哪里吗?
<html>
<head>
<script>
function alpha()
{
var x = document.getElementById('input1');
var y = x.value;
var z = isNaN(y);
if(z<1 || z>10){console.log("Invalid");} else {console.log("valid");}
}
</script>
</head>
<body>
<button id="but1" onmouseover="alpha()" style="background:blue;">Click Me</button>
<p id=para1> Hello! This is paragraph One! </p>
<input type=text id=input1 >
</body>
</html>
提前致谢,很抱歉提出愚蠢的问题!但是,我找不到代码哪里出错了!
isNaN
returns 一个布尔值,并将其与数字进行比较。您需要将 x
与您的范围进行比较。
if(z || x<1 || x>10)
这里是我将如何清理你的代码
function alpha(){
//name your variables something meaningful
var userInputField = document.getElementById('input1');
//using parse int tells yourself and future programmers you want an int
//it also gives you NaN if it's not a number so you don't have to check yourself
//the 10 is the radix you want to convert to
var userInputedValue = parseInt(x.value,10);
//check explicitly for NaN will save you some headaches
if(userInputedValue === NaN || userInputedValue<1 || userInputedValue>10){
console.log("Invalid");
} else {
console.log("valid");
}
}