在这个例子中,我们假设我们有一个文本框,并且要求只允许5到15之间的数值。此外,我们必须验证keyup和blur。在这种情况下,我们假设用户试图输入数字12.我们现在不用担心!$。isNumeric()等。你明白了。两个事件都在第一个击键时触发并失败,因为1是< 5.用户必须能够输入12. \ m / \ m /
var bAlertCalled = false;
$("someTextbox").on('keyup blur', function (e) {
if (validateRange(5, 15, parseInt($(this().val()))) === false) {
$(this).focus();
}
else {
// Valid range entered. Do something.
}
});
function validateRange(iRangeMin, iRangeMax, iValue) {
// Both keyup and blur will fire. This prevents 2 alerts from displaying.
if (bAlertCalled === true) {
bAlertCalled = false;
return;
}
if ((iValue < iRangeMin) || (iValue > iRangeMax)) {
bAlertCalled = true;
alert('Please enter a numeric value between 5 and 15.');
return false;
}
else {
return true;
}
}
答案 0 :(得分:0)
感谢您的所有投入。一些好的想法有助于解决问题。这是一些伪代码。
var bAlertCalled = false;
$("someTextbox").on('keyup blur', function (e) {
// Both keyup and blur will fire. This prevents 2 alerts from displaying.
if (bAlertCalled === true) {
bAlertCalled = false;
return;
}
if ($(this).val().length > 0) {
var obj = $(this);
delay(function () {
if (validateRange(5, 15, parseInt(obj.val())) === false) {
obj.select();
}
else {
// Valid range entered. Do something.
}
}, 500);
}
});
function validateRange(iRangeMin, iRangeMax, iValue) {
if ((iValue < iRangeMin) || (iValue > iRangeMax)) {
bAlertCalled = true;
alert('Please enter a numeric value between 5 and 15.');
return false;
}
else {
return true;
}
}
var delay = (function () {
var timer = 0;
return function (callback, ms) {
clearTimeout(timer);
timer = setTimeout(callback, ms);
};
})();