gpt4 book ai didi

Javascript验证函数总是回复无效

转载 作者:行者123 更新时间:2023-12-02 16:30:15 25 4
gpt4 key购买 nike

我已经完成了所有正确的操作,但对于所有值,该函数仅显示“无效”。有人能告诉我问题出在哪里吗?

<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 返回一个 bool 值并将其与数字进行比较。您需要将 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");
}
}

关于Javascript验证函数总是回复无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28375847/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com