我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。

我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。

在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。

我该怎么做呢?


当前回答

下面是我写的一个建议,它可以处理表单中的多个输入。

这个函数获取输入字段的Object,放到你的代码中

function fieldKeyup(obj){
    //  what you want this to do

} // fieldKeyup

这是实际的delayCall函数,负责多个输入字段

function delayCall(obj,ms,fn){
    return $(obj).each(function(){
    if ( typeof this.timer == 'undefined' ) {
       // Define an array to keep track of all fields needed delays
       // This is in order to make this a multiple delay handling     
          function
        this.timer = new Array();
    }
    var obj = this;
    if (this.timer[obj.id]){
        clearTimeout(this.timer[obj.id]);
        delete(this.timer[obj.id]);
    }

    this.timer[obj.id] = setTimeout(function(){
        fn(obj);}, ms);
    });
}; // delayCall

用法:

$("#username").on("keyup",function(){
    delayCall($(this),500,fieldKeyup);
});

其他回答

今天看到这个有点晚,但我想把它放在这里,以防有人需要。只需将函数分离以使其可重用。下面的代码在输入stop后将等待1/2秒。

    var timeOutVar
$(selector).on('keyup', function() {

                    clearTimeout(timeOutVar);
                    timeOutVar= setTimeout(function(){ console.log("Hello"); }, 500);
                });

好吧,我也做了一段代码限制高频ajax请求由Keyup / Keydown。看看这个:

https://github.com/raincious/jQueue

像这样提问:

var q = new jQueue(function(type, name, callback) {
    return $.post("/api/account/user_existed/", {Method: type, Value: name}).done(callback);
}, 'Flush', 1500); // Make sure use Flush mode.

并像这样绑定事件:

$('#field-username').keyup(function() {
    q.run('Username', this.val(), function() { /* calling back */ });
});

jQuery:

变量超时 = 空; $('#input').keyup(function() { 清除超时(超时); 超时 = 设置超时(() => { console.log($(this).val()); }, 1000); }); <script src=“https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.4/jquery.min.js”></script> <输入类型=“文本” id=“输入” 占位符=“在此处键入...”/>

纯Javascript:

let input = document.getElementById('input'); 让timeout = null; 输入。addEventListener('keyup',函数(e) { clearTimeout(超时); timeout = setTimeout(函数(){ console.log(价值:,input.value); }, 1000); }); <input type="text" id="input" placeholder=" type here…"/>

看一下autocomplete插件。我知道它允许您指定延迟或最小字符数。即使你最终没有使用这个插件,浏览代码也会给你一些关于如何自己实现它的想法。

解释

使用变量存储超时函数。然后使用clearTimeout()清除该变量的任何活动超时函数,然后使用setTimeout()再次设置活动超时函数。我们首先运行clearTimeout(),因为如果用户键入“hello”,我们希望函数在用户按下“o”键后不久运行(而不是每个字母一次)。

演示工作

超级简单的方法,设计用于在用户在文本字段中输入完成后运行一个函数…

$(document).ready(function(e) { var timeout; var delay = 2000; // 2 seconds $('.text-input').keyup(function(e) { $('#status').html("User started typing!"); if(timeout) { clearTimeout(timeout); } timeout = setTimeout(function() { myFunction(); }, delay); }); function myFunction() { $('#status').html("Executing function for user!"); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> Status: <span id="status">Default Status</span><br> <textarea name="text-input" class="text-input"></textarea>