Facebook Style AJAX Search

后端 未结 3 1277
清酒与你
清酒与你 2020-12-13 16:51

I\'ve created a Facebook style ajax search for my site where as you type it will bring up the results in a nice list below your search.

$(\"#s\").keyup(funct         


        
3条回答
  •  北海茫月
    2020-12-13 17:22

    the method you are referring to is called "Debouncing"

    I usually have a "Debounce" function at the bottom of all my scripts

    var debounce=function(func, threshold, execAsap) {
        var timeout;
        return function debounced () {
            var obj = this, args = arguments;
            function delayed () {
                if (!execAsap)
                    func.apply(obj, args);
                timeout = null; 
            };
            if (timeout)
                clearTimeout(timeout);
            else if (execAsap)
                func.apply(obj, args);
            timeout = setTimeout(delayed, threshold || 100); 
        }; 
    };
    

    And then whenever I do anything that will benefit from a debounce I can use it generically

    So your code would be re-written as

    $("#s").keyup(debounce(function() {
        var searchbox = $(this).val();
        var dataString = 's='+ searchbox;
        if(searchbox!='') {
            $.ajax({
                    type: "POST",
                    url: "/livesearch.php",
                    data: dataString,
                    cache: false,
                    success: function(html){
                            $("#display").html(html).show();
                    }
            });
        } else {return false; }  
    }
    ,350 /*determines the delay in ms*/
    ,false /*should it execute on first keyup event, 
           or delay the first event until 
           the value in ms specified above*/
    ));
    

提交回复
热议问题