我有一个文本框,需要同时进行击键和模糊事件验证。如果我输入“ X”,则两个事件都将触发,并且显然,您将基于以下代码看到两个警报。需要keyup事件,因为我可能会基于有效值触发一些操作,并且还需要保持模糊事件,以防按Tab键。目标是在此处显示一个警报。\ m / \ m /
$("#txtLength").on('keyup blur', function (e) {
if ($(this).val().length > 0) {
switch (true) {
case !$.isNumeric($(this).val()):
alert("Please enter a numeric value.");
$(this).focus();
break
case ($(this).val() < 5) || ($(this).val() > 10):
alert("Length must be a numeric value between 5 and 10.");
$(this).focus();
break;
default:
}
}
});
Run Code Online (Sandbox Code Playgroud)
感谢您的所有投入。一些好的想法有助于解决问题。坚持主题,避免在按键和模糊时使用.on来显示两个警报,这就是我最后要做的事情。
var bAlertCalled = false;
$("#txtLength").on('keyup blur', function (e) {
if (bAlertCalled === true) {
bAlertCalled = false;
return;
}
if ($(this).val().length > 0) {
var iLength = parseInt($(this).val());
switch (true) {
case !$.isNumeric($(this).val()):
bAlertCalled = true;
$(this).focus();
alert("Please enter a numeric value.");
break
case (iLength < 5) || (iLength > 10):
bAlertCalled = true;
$(this).focus();
alert("Length must be a numeric value between 5 and 10.");
break;
default:
}
}
});
Run Code Online (Sandbox Code Playgroud)