How do I make my live jQuery search wait a second before performing the search?

前端 未结 6 2043
灰色年华
灰色年华 2020-12-13 04:52

I\'ve got a search input which sends data from an input to a php file as I type. The php file does a search on my database and shows up a list of search options. You know, t

6条回答
  •  北海茫月
    2020-12-13 05:40

    I have found the best success when attaching the event to keypress, keydown, and keyup inputs. Safari/FireFox/IE all seem to handle special keypresses (delete, backspace, etc.) a bit differently but using all events together seems to cover it. The only way that running all events works though is to use setTimeout so that when they all fire it just resets the timer and ultimately the callback only gets executed once.

    var delay = 200;
    var search_timer = null;
    $("#searchMe").keydown(function(e) {
        if(search_timer) {
            clearTimeout(search_timer);
        }
        search_timer = setTimeout(lookup, delay);
    });
    $("#searchMe").keypress(function(e) {
        if(search_timer) {
            clearTimeout(search_timer);
        }
        search_timer = setTimeout(lookup, delay);
    });
    $("#searchMe").keyup(function(e) {
        if(search_timer) {
            clearTimeout(search_timer);
        }
        search_timer = setTimeout(lookup, delay);
    });
    

提交回复
热议问题