最快的方法实际上是使用 keydown 事件。(它作用于键被按下而不是被释放,这总是更快。)
var timer;
$(".prod-name-input").keydown(function(){
var self = this;
clearTimeout(timer);
timer = setTimeout(function(){
$(".smart-suggestions").load('invoice-get-data.php?searchword=' + self.value);
},250);
});
如果用户停止输入超过 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);
});