jQuery计时器对输入不起作用

jQuery timer not working on input

本文关键字:不起作用 输入 计时器 jQuery      更新时间:2024-01-22

在用户停止键入以检查输入是否满足最小长度要求3秒后,我试图激发一个事件。如果是,则显示为有效,如果少于14个字符则显示为无效/错误。我希望onkeydown清除计时器,检查是否为正验证,如果它无法启动另一个计时器。

var typingTimer;                //timer identifier
var doneTypingInterval = 3000;  //time in ms, 3 second for example
// on keydown, start the countdown
$('#contact_phone').keydown(function(){
clearTimeout(typingTimer);
if ($('#contact_phone').val().length == 14) {
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
}
});
//user is "finished typing," do something
function doneTyping () {
$('#contact_phone').keyup(function() {
    if ($(this).val().length == 14) {
        $(this).removeClass('whiteBorder').removeClass('error').addClass('valid');
    } else {
        $(this).removeClass('whiteBorder').removeClass('valid').addClass('error');
    }
});
}

每次定时器到期时,都会绑定keyup事件

您不需要将两个事件都绑定到输入。'删除keydown并将其替换为keyup事件。

var typingTimer; //timer identifier
var doneTypingInterval = 3000; //time in ms, 5 second for example
// on keydown, start the countdown
$('#contact_phone').keyup(function () {
    clearTimeout(typingTimer);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});
//user is "finished typing," do something
function doneTyping() {
    var $this = $('#contact_phone');
    if ($this.val().length == 14) {
        $this.removeClass('whiteBorder').removeClass('error').addClass('valid');
    } else {
        $this.removeClass('whiteBorder').removeClass('valid').addClass('error');
    }
}

检查Fiddle

问题是您要等到用户停止键入绑定keyup事件之后。由于用户已停止键入。。。这个事件永远不会发生。

尝试:

// on keydown, start the countdown
$('#contact_phone').keydown(function () {
    var $input= $(this);
    clearTimeout(typingTimer);
    if ($('#contact_phone').val().length == 14) {
        typingTimer = setTimeout(function () {
            doneTyping($input);
        }, doneTypingInterval);
    }
});
//user is "finished typing," do something
function doneTyping($input) {
        if ($input.val().length == 14) {
            $input.removeClass('whiteBorder').removeClass('error').addClass('valid');
        } else {
           $input.removeClass('whiteBorder').removeClass('valid').addClass('error');
        }
}