【发布时间】:2016-02-13 01:36:34
【问题描述】:
我建立了一个类似于谷歌搜索的即时搜索功能。一个 setTimeout 函数用于去抖动/限制搜索。但是,我不希望第一次执行 searchq() 函数的延迟。如何修改代码来实现这一点?
var timeout = null;
function doDelayedSearch(txt) {
if (timeout) {
clearTimeout(timeout);
}
timeout = setTimeout(function() {
searchq(txt); //this is the search function (posting and fetching result)
}, 1000);
}
function searchq(txt){
// get the value
// txt = $("input").val();
// post the value
if(txt){
$.post("search.php", {searchVal: txt}, function(result){
$("#search_output").html(result+"<br><a class='anchor_tag_s' href='createobject.php?object="+txt+"'><div id='notfound'>Not found above? Create Here.</div><a>");
});
}
else{
$("#search_output").html("");
}
};
【问题讨论】:
-
顺便说一句,请注意您不需要
if (timeout),您可以直接拨打clearTimeout()。您的 if 条件 每次 都会为真,除非第一次调用doDelayedSearch(),因为timeout永远不会被设置回假值。使用 null 值或使用已完成或取消超时的 id 调用clearTimeout()没有任何害处。
标签: javascript jquery html search