首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何在停止输入/写入后触发输入文本中的事件?

如何在停止输入/写入后触发输入文本中的事件?
EN

Stack Overflow用户
提问于 2012-12-26 22:48:12
回答 13查看 142.2K关注 0票数 87

我想在停止在输入文本框中键入(而不是在键入时)字符后立即触发事件。

我已经尝试过了:

代码语言:javascript
复制
$('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请求。

On this fiddle我用一个简单的警报而不是AJAX演示了同样的问题。

有没有解决这个问题的方法,或者我只是用了一个不好的方法?

EN

回答 13

Stack Overflow用户

回答已采纳

发布于 2012-12-26 22:52:31

您必须使用setTimeout (就像您一样),但也要存储引用,这样您就可以不断地重新设置限制。类似于:

代码语言:javascript
复制
//
// $('#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()));
});
代码语言:javascript
复制
<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>

它将在以下情况下执行:

超时已过,或

  • user switched fields (blur event)

(以先到者为准)

票数 174
EN

Stack Overflow用户

发布于 2013-08-28 18:00:24

解决方案:

以下是解决方案。在用户停止键入指定时间后执行函数:

代码语言:javascript
复制
var delay = (function(){
  var timer = 0;
  return function(callback, ms){
  clearTimeout (timer);
  timer = setTimeout(callback, ms);
 };
})();

用法

代码语言:javascript
复制
$('input').keyup(function() {
  delay(function(){
    alert('Hi, func called');
  }, 1000 );
});
票数 77
EN

Stack Overflow用户

发布于 2014-06-12 01:06:19

你可以使用underscore.js的“去反弹”。

代码语言:javascript
复制
$('input#username').keypress( _.debounce( function(){<your ajax call here>}, 500 ) );

这意味着您的函数调用将在按下一个键500毫秒后执行。但是如果你在500ms之前按下另一个键(另一个按键事件被触发),之前的函数执行将被忽略(去抖动),新的函数将在新的500ms计时器之后执行。

对于额外的信息,使用_.debounce(func,timer,true)将意味着第一个函数将被执行,随后500ms计时器的所有其他按键事件将被忽略。

票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14042193

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档