Moh*_*mad 7 jquery throttling delay
我正在使用以下代码(由另一个用户编写)来限制livesearch函数中的ajax请求:
JSFiddle如果您更喜欢演示:http://jsfiddle.net/4xLVp/
但是,这似乎有点儿麻烦.清除值Ctrl+shift+back-arrow,然后再次键入会导致一连串请求.空值也会导致请求.它看起来似乎不对,特别是与jQuery UI自动完成相比,其中请求延迟似乎更加严格.
$('##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*/ }
});
Run Code Online (Sandbox Code Playgroud)
有没有更好的方法来处理这个?
我会用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*/ }
});
}());
Run Code Online (Sandbox Code Playgroud)
还有一个去抖/油门插件.
| 归档时间: |
|
| 查看次数: |
5066 次 |
| 最近记录: |