[英]Why javascript IF/ELSE doesn't work properly?
我是JavaScript的新手,我想在注册表格上进行用户名验证。 我不知道我的代码有什么问题,但是我认为“ IF ELSE”语句有问题。
$(document).ready(function() {
$("#usernameErrorMsg").hide();
var usernameLength = $("#username").length;
$("#username").focusout(function() {
checkUser();
});
function checkUser() {
if (usernameLength < 5 || usernameLength > 20) {
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
}
});
我希望当我输入超过5个字符直到20个字符时,usernameErrorMsg会消失。 实际结果,无论我输入了多少个字符,错误消息都会不断出现。
在运行checkUser()
之前, usernameLength
仅被计算一次。 您应该每次在回调中重新计算其值; 否则,对该值的更改将在回调内部不可见。
此外,如果要在输入中检查测试的长度,则需要检查$("#username").val().length
,而不是$("#username").length
:
function checkUser(){
var usernameLength = $("#username").val().length;
if (usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
} else {
$("#usernameErrorMsg").hide();
}
}
$("#username").length
不是字段中字符的长度。 它是查询返回的JQuery包装集中的元素数量。 由于只有一个元素的id
为username
,因此长度始终为1
而if
条件始终为true
。
您要做的就是获取字段中值的长度:
$("#username").val().length
您还需要将获取值的行移至focusout
事件处理程序中,以便始终使用最新数据。
最后,让一个函数不执行任何操作而只调用另一个函数并没有多大意义,因此您可以将checkUser
函数与事件回调结合起来并简化代码。
$(document).ready(function() { $("#usernameErrorMsg").hide(); var username = $("#username"); // Find the element just once $("#username").focusout(function() { // Each time the user leaves the field, get the current // amount of characters in the input field var usernameLength = username.val().length; // See the difference between the length of the JQuery query and // the length of the value of the first element in the results? console.log(username.length, usernameLength); if (usernameLength < 5 || usernameLength > 20) { $("#usernameErrorMsg").show(); } else { $("#usernameErrorMsg").hide(); } }); });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> Enter your name: <input id="username"> <span id="usernameErrorMsg">ERROR</span>
每次函数检查时,您都需要获取input
的length
。
目前,您只计算一次length
。
$(document).ready(function(){
$("#usernameErrorMsg").hide();
$("#username").focusout(function(){
checkUser();
});
function checkUser(){
//calculate the length everytime in the function
var usernameLength = $("#username").val().length;
if(usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
}
else{
$("#usernameErrorMsg").hide();
}
}
尝试这个
$(document).ready(function(){
$("#usernameErrorMsg").hide();
$("#username").focusout(function(){
checkUser();
});
function checkUser(){
usernameLength = $("#username").length;
if(usernameLength < 5 || usernameLength > 20){
$("#usernameErrorMsg").show();
}
else{
$("#usernameErrorMsg").hide();
}
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.