7

我正在使用以下代码(由另一个用户编写)来限制 livesearch 函数中的 ajax 请求:

JSFiddle 如果您喜欢演示:http: //jsfiddle.net/4xLVp/

不过,这似乎是错误的。用 清除值Ctrl+shift+back-arrow,然后再次键入会引起一连串的请求。空白值也会导致请求。它看起来不太对劲,尤其是与jQuery UI autocomplete相比,请求延迟似乎更加可衡量。

    $('##tag-search').keyup(function() {
        var elem = $(this);
        if (elem.val().length >= 2) {
            elem.data('search',search).clearQueue().stop().delay(1000).queue(function() {
                $.ajax({ // ajax stuff
                    'success': function(data){ /*show result*/ }
                });
                if (elem.data('search') !=  string) return;
            });                                             
        } else if (string.length <= 1) { /*show original content*/ }
    });

有没有更好的方法来处理这个?

4

1 回答 1

7

我只会使用setTimeout

(function() {
    var timeout;
    $('#tag-search').keyup( function() {
        var elem = $(this);
        if (elem.val().length >= 2) {
            clearTimeout(timeout);
            timeout = setTimeout(function() {
               $.ajax({ // ajax stuff
                    'success': function(data){ /*show result*/ }
                });     
            }, 80); // <-- choose some sensible value here                                      
        } else if (string.length <= 1) { /*show original content*/ }
    });
}());

还有一个debounce/throttle插件。

于 2011-08-06T15:43:59.693 回答