Javascript 带计时器的OnKeyUp事件?
JQuery对我来说有点陌生,我使用ajax建立了一个搜索建议系统,它工作得很好,但由于onKeyUp的限制,它的工作速度非常慢。经过一些阅读,我发现我可以设置一个计时器的事件。所以我要做的是在'prod name input'输入字段onKeyUp事件上设置一个计时器,以便每2秒调用一次。我在网上找到了一些这样的例子,但我没能成功地将其中任何一个应用到我的代码中,我想知道是否有人能告诉我这是如何工作的?非常感谢 我的输入字段Javascript 带计时器的OnKeyUp事件?,javascript,jquery,Javascript,Jquery,JQuery对我来说有点陌生,我使用ajax建立了一个搜索建议系统,它工作得很好,但由于onKeyUp的限制,它的工作速度非常慢。经过一些阅读,我发现我可以设置一个计时器的事件。所以我要做的是在'prod name input'输入字段onKeyUp事件上设置一个计时器,以便每2秒调用一次。我在网上找到了一些这样的例子,但我没能成功地将其中任何一个应用到我的代码中,我想知道是否有人能告诉我这是如何工作的?非常感谢 我的输入字段 <input onKeyUp="search(this.val
<input onKeyUp="search(this.value)" type="text" class="prod-name-input"/>
实际上,最快的方法是使用keydown事件。(它在按键按下时起作用,而不是在按键释放时起作用,释放总是更快。) 如果用户停止键入超过1/4秒,则加载结果。如果发生的请求太多,请将延迟增加到500 我将用注释逐行检查代码:
// declare a variable that will hold a reference to the timer we create
var timer;
// bind a keydown event to all existing elements that have the prod-name-input class
$(".prod-name-input").keydown(function(){
// store a reference to the clicked element so we can access it inside of setTimeout()
var self = this;
// clear existing timer stored in the timer variable (if any)
clearTimeout(timer);
// create a new timer and store it in the timer variable
timer = setTimeout(function(){
// load content
$(".smart-suggestions").load('invoice-get-data.php?searchword=' + self.value);
// give the timer a 250ms delay (0.25 seconds or 1/4 of a second)
},250);
});
实际上,最快的方法是使用keydown事件。(它在按键按下时起作用,而不是在按键释放时起作用,释放总是更快。) 如果用户停止键入超过1/4秒,则加载结果。如果发生的请求太多,请将延迟增加到500 我将用注释逐行检查代码:
// declare a variable that will hold a reference to the timer we create
var timer;
// bind a keydown event to all existing elements that have the prod-name-input class
$(".prod-name-input").keydown(function(){
// store a reference to the clicked element so we can access it inside of setTimeout()
var self = this;
// clear existing timer stored in the timer variable (if any)
clearTimeout(timer);
// create a new timer and store it in the timer variable
timer = setTimeout(function(){
// load content
$(".smart-suggestions").load('invoice-get-data.php?searchword=' + self.value);
// give the timer a 250ms delay (0.25 seconds or 1/4 of a second)
},250);
});
Underline.js中有一个throttle函数处理此场景。您可以查看它们的确切代码,或者如果您在项目中使用下划线.js,则可以查看一些使用说明文件在下划线.js中有一个节流函数来处理此场景。您可以查看它们的确切代码,或者如果在项目中使用下划线.js,则可以查看一些使用说明文档
// declare a variable that will hold a reference to the timer we create
var timer;
// bind a keydown event to all existing elements that have the prod-name-input class
$(".prod-name-input").keydown(function(){
// store a reference to the clicked element so we can access it inside of setTimeout()
var self = this;
// clear existing timer stored in the timer variable (if any)
clearTimeout(timer);
// create a new timer and store it in the timer variable
timer = setTimeout(function(){
// load content
$(".smart-suggestions").load('invoice-get-data.php?searchword=' + self.value);
// give the timer a 250ms delay (0.25 seconds or 1/4 of a second)
},250);
});