简体   繁体   English

Javascript中的即时搜索功能

[英]Instant search function in Javascript

I am using the following javascript for my instant search function (to detect when the visitor stops writing, so the function won't run on every single keyup). 我使用以下javascript作为我的即时搜索功能(以检测访问者何时停止写入,因此该功能不会在每个单独的键盘上运行)。

It works but it's more delay than 1000 milliseconds. 它工作但它延迟超过1000毫秒。 Even if I set it to 200 milliseconds it's 1-2 seconds delay before the instant search function runs. 即使我将其设置为200毫秒,它也会在即时搜索功能运行之前延迟1-2秒。

Is there a better/faster way to detect when the visitor has stopped typing in the input (I only need it for Internet Explorer if that's make any difference). 是否有更好/更快的方法来检测访问者何时停止输入输入(如果这有任何区别,我只需要它用于Internet Explorer)。

$(document).ready(function(){

var delay = (function(){
var timer = 0;
return function(callback, ms){
clearTimeout (timer);
timer = setTimeout(callback, ms);
};
})();

$('input').keyup(function() {
delay(function(){
//instant search function here
}, 1000 );
});

});

New idea: When I think about it the problem is that I can't continue writing in the input filed when the function runs. 新想法:当我想到它时,问题是当函数运行时我无法继续在输入字段中写入。 Any solution for that and I will not be needing any delay function. 任何解决方案,我将不需要任何延迟功能。

function instantSearch(){ ... }

var timer;
$('input').keyup(function(){
   timer && clearTimeout(timer);
   timer = setTimeout(instantSearch, 200);
});

If you're using the keyup event it shouldn't be necessary to specify a delay unless there are specific limits on queries-per-second or something similar. 如果您正在使用keyup事件,则除非对每秒查询或类似事件有特定限制,否则不必指定延迟。

There's a fairly concise walkthrough here: http://blog.comperiosearch.com/2012/06/make-an-instant-search-application-using-json-ajax-and-jquery/ 这里有一个相当简洁的演练: http//blog.comperiosearch.com/2012/06/make-an-instant-search-application-using-json-ajax-and-jquery/

Is your instant search function making an AJAX request to return results? 您的即时搜索功能是否发出AJAX请求以返回结果? That might be the difference between setting the delay to 200ms and getting your response back 1-2s later. 这可能是将延迟设置为200毫秒并在1-2秒之后将响应恢复的差异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM