twitter-bootstrap Twitter 引导输入延迟
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17318350/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Twitter bootstrap typeahead delay
提问by Maki
I use twitter bootstrap typeahead for displaying some data from server, the problem is when user types an letter typeahead makes an ajax call to server and when I try to type 2 or 3 letters fast it will make 2 or 3 ajax calls to server, is there a possibility to make an delay when user is typing letters to make only one ajax call to server
我使用 twitter bootstrap typeahead 来显示来自服务器的一些数据,问题是当用户输入一个字母 typeahead 对服务器进行 ajax 调用时,当我尝试快速输入 2 或 3 个字母时,它将对服务器进行 2 或 3 次 ajax 调用,是当用户键入字母以仅对服务器进行一次 ajax 调用时,可能会延迟
my code at the moment:
我现在的代码:
$('#SEARCH-INPUT').typeahead({
source: function (query, process) {
jQuery.ajax({
type: "GET",
url: "/organisations/search",
data: {search_name: $("#SEARCH-INPUT").val()},
beforeSend: function(){
$("#SEARCH-LOADING").show();
},
success: function (data) {
organisations = [];
organisations_hash = {};
$.each(data, function(i, item){
organisations_hash[item.name.toUpperCase()] = item.id;
organisations.push(item.name);
});
organisations.sort();
$("#SEARCH-LOADING").addClass("hidden");
process(organisations);
},
error: function (){ alert("error");},
async: false
});
}
,updater: function (item) {
$("#SEARCH-INPUT").val(item);
$("#SEARCH-BUTTON").click();
return item;
}
,items: 9
,minLength: 1
});
回答by MrBoolean
Use this solution:
使用此解决方案:
(function() {
var timeout;
$('[name="fill"]').typeahead({
source: function(value) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
alert(value);
}, 300);
}
});
})();
See in action:
见实战:
setTimeout and clearTime works fine!
setTimeout 和 clearTime 工作正常!

