我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。
我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。
在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。
我该怎么做呢?
我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。
我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。
在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。
我该怎么做呢?
当前回答
使用jQuery插件bindWithDelay:
element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)
其他回答
好吧,我也做了一段代码限制高频ajax请求由Keyup / Keydown。看看这个:
https://github.com/raincious/jQueue
像这样提问:
var q = new jQueue(function(type, name, callback) {
return $.post("/api/account/user_existed/", {Method: type, Value: name}).done(callback);
}, 'Flush', 1500); // Make sure use Flush mode.
并像这样绑定事件:
$('#field-username').keyup(function() {
q.run('Username', this.val(), function() { /* calling back */ });
});
如果你想在一段时间后做一些事情,并在特定的事件(如keyup)后重置定时器,最好的解决方案是使用clearTimeout和setTimeout方法:
// declare the timeout variable out of the event listener or in the global scope
var timeout = null;
$(".some-class-or-selector-to-bind-event").keyup(function() {
clearTimeout(timout); // this will clear the recursive unneccessary calls
timeout = setTimeout(() => {
// do something: send an ajax or call a function here
}, 2000);
// wait two seconds
});
如果有人喜欢延迟相同的函数,并且没有外部变量,他可以使用下一个脚本:
function MyFunction() {
//Delaying the function execute
if (this.timer) {
window.clearTimeout(this.timer);
}
this.timer = window.setTimeout(function() {
//Execute the function code here...
}, 500);
}
你也可以看看underscore.js,它提供了像debounce这样的实用方法:
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
这对我来说很有效,我延迟了搜索逻辑操作,并检查值是否与文本字段中输入的值相同。如果值相同,则继续执行与搜索值相关的数据的操作。
$('#searchText').on('keyup',function () {
var searchValue = $(this).val();
setTimeout(function(){
if(searchValue == $('#searchText').val() && searchValue != null && searchValue != "") {
// logic to fetch data based on searchValue
}
else if(searchValue == ''){
// logic to load all the data
}
},300);
});