停止键入/书写后,如何在输入文本中触发事件? [英] How to trigger an event in input text after I stop typing/writing?

查看:68
本文介绍了停止键入/书写后,如何在输入文本中触发事件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在我停止在输入文本框中输入字符(而不是在输入字符时)之后触发一个事件.

I want to trigger an event just after I stop typing (not while typing) characters in my input textbox.

我尝试过:

$('input#username').keypress(function() {
    var _this = $(this); // copy of this object for further usage

    setTimeout(function() {
        $.post('/ajax/fetch', {
            type: 'username',
            value: _this.val()
        }, function(data) {
            if(!data.success) {
                // continue working
            } else {
                // throw an error
            }
        }, 'json');
    }, 3000);
});

但是此示例为每个键入的字符产生一个超时,如果我输入20个字符,我将收到大约20个AJAX请求.

But this example produces a timeout for every typed character and I get about 20 AJAX requests if I type-in 20 characters.

在这个小提琴上我用一个简单的警报而不是AJAX演示了同样的问题.

On this fiddle I demonstrate the same problem with a simple alert instead of an AJAX.

是否有解决方案,或者我使用的方法很糟糕?

推荐答案

您将不得不使用setTimeout(就像您一样),而且还必须存储引用,以便您可以继续重置限制.像这样:

You'll have to use a setTimeout (like you are) but also store the reference so you can keep resetting the limit. Something like:

//
// $('#element').donetyping(callback[, timeout=1000])
// Fires callback when a user has finished typing. This is determined by the time elapsed
// since the last keystroke and timeout parameter or the blur event--whichever comes first.
//   @callback: function to be called when even triggers
//   @timeout:  (default=1000) timeout, in ms, to to wait before triggering event if not
//              caused by blur.
// Requires jQuery 1.7+
//
;(function($){
    $.fn.extend({
        donetyping: function(callback,timeout){
            timeout = timeout || 1e3; // 1 second default timeout
            var timeoutReference,
                doneTyping = function(el){
                    if (!timeoutReference) return;
                    timeoutReference = null;
                    callback.call(el);
                };
            return this.each(function(i,el){
                var $el = $(el);
                // Chrome Fix (Use keyup over keypress to detect backspace)
                // thank you @palerdot
                $el.is(':input') && $el.on('keyup keypress paste',function(e){
                    // This catches the backspace button in chrome, but also prevents
                    // the event from triggering too preemptively. Without this line,
                    // using tab/shift+tab will make the focused element fire the callback.
                    if (e.type=='keyup' && e.keyCode!=8) return;
                    
                    // Check if timeout has been set. If it has, "reset" the clock and
                    // start over again.
                    if (timeoutReference) clearTimeout(timeoutReference);
                    timeoutReference = setTimeout(function(){
                        // if we made it here, our timeout has elapsed. Fire the
                        // callback
                        doneTyping(el);
                    }, timeout);
                }).on('blur',function(){
                    // If we can, fire the event since we're leaving the field
                    doneTyping(el);
                });
            });
        }
    });
})(jQuery);

$('#example').donetyping(function(){
  $('#example-output').text('Event last fired @ ' + (new Date().toUTCString()));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<input type="text" id="example" />
<p id="example-output">Nothing yet</p>

该操作将在以下时间执行:

That will execute when:

  1. 超时已经过去,或者
  2. 用户切换的字段(blur事件)
  1. The timeout has elapsed, or
  2. The user switched fields (blur event)

(以先到者为准)

这篇关于停止键入/书写后,如何在输入文本中触发事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆