How to delay the .keyup() handler until the user stops typing?

前端 未结 27 2574
半阙折子戏
半阙折子戏 2020-11-21 23:32

I’ve got a search field. Right now it searches for every keyup. So if someone types “Windows”, it will make a search with AJAX for every keyup: “W”, “Wi”, “Win”, “Wind”, “Wi

27条回答
  •  执笔经年
    2020-11-22 00:18

    This function extends the function from Gaten's answer a bit in order to get the element back:

    $.fn.delayKeyup = function(callback, ms){
        var timer = 0;
        var el = $(this);
        $(this).keyup(function(){                   
        clearTimeout (timer);
        timer = setTimeout(function(){
            callback(el)
            }, ms);
        });
        return $(this);
    };
    
    $('#input').delayKeyup(function(el){
        //alert(el.val());
        // Here I need the input element (value for ajax call) for further process
    },1000);
    

    http://jsfiddle.net/Us9bu/2/

提交回复
热议问题