Javascript验证函数总是回复无效

Javascript validation function always replying invalid

本文关键字:回复 无效 验证 函数 Javascript      更新时间:2023-09-26

我已经做了所有正确的事情,但对于所有值,函数仅显示"无效"。有人能告诉我问题出在哪里吗?

<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返回一个布尔值,并将其与数字进行比较。您需要将CCD_ 2与您的范围进行比较。

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");
    }
}