我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。
我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。
在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。
我该怎么做呢?
我有一个搜索域。现在它会搜索每一个按键。所以如果有人输入“Windows”,它会用AJAX搜索每个键:“W”,“Wi”,“Win”,“Wind”,“Windo”,“Window”,“Windows”。
我想有一个延迟,所以它只在用户停止输入200毫秒时搜索。
在keyup函数中没有这个选项,我尝试了setTimeout,但它不起作用。
我该怎么做呢?
当前回答
这对我来说很有效,我延迟了搜索逻辑操作,并检查值是否与文本字段中输入的值相同。如果值相同,则继续执行与搜索值相关的数据的操作。
$('#searchText').on('keyup',function () {
var searchValue = $(this).val();
setTimeout(function(){
if(searchValue == $('#searchText').val() && searchValue != null && searchValue != "") {
// logic to fetch data based on searchValue
}
else if(searchValue == ''){
// logic to load all the data
}
},300);
});
其他回答
好吧,我也做了一段代码限制高频ajax请求由Keyup / Keydown。看看这个:
https://github.com/raincious/jQueue
像这样提问:
var q = new jQueue(function(type, name, callback) {
return $.post("/api/account/user_existed/", {Method: type, Value: name}).done(callback);
}, 'Flush', 1500); // Make sure use Flush mode.
并像这样绑定事件:
$('#field-username').keyup(function() {
q.run('Username', this.val(), function() { /* calling back */ });
});
你也可以看看underscore.js,它提供了像debounce这样的实用方法:
var lazyLayout = _.debounce(calculateLayout, 300);
$(window).resize(lazyLayout);
我使用这个小函数也是出于同样的目的,在用户停止输入一段特定的时间后,或者在以高速率触发的事件中执行一个函数,比如resize:
function delay(callback, ms) { var timer = 0; return function() { var context = this, args = arguments; clearTimeout(timer); timer = setTimeout(function () { callback.apply(context, args); }, ms || 0); }; } // Example usage: $('#input').keyup(delay(function (e) { console.log('Time elapsed!', this.value); }, 500)); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <label for="input">Try it: <input id="input" type="text" placeholder="Type something here..."/> </label>
工作原理:
delay函数将返回一个内部处理单个计时器的包装函数,在每次执行时,计时器都会根据所提供的时间延迟重新启动,如果在此时间之前发生多次执行,计时器将重置并重新启动。
当计时器最终结束时,执行回调函数,传递原始上下文和参数(在本例中,是jQuery的事件对象和DOM元素)。
更新2019-05-16
我在现代环境中使用ES5和ES6特性重新实现了该功能:
function delay(fn, ms) {
let timer = 0
return function(...args) {
clearTimeout(timer)
timer = setTimeout(fn.bind(this, ...args), ms || 0)
}
}
该实现包含一组测试。
对于更复杂的东西,看看jQuery Typewatch插件。
解释
使用变量存储超时函数。然后使用clearTimeout()清除该变量的任何活动超时函数,然后使用setTimeout()再次设置活动超时函数。我们首先运行clearTimeout(),因为如果用户键入“hello”,我们希望函数在用户按下“o”键后不久运行(而不是每个字母一次)。
演示工作
超级简单的方法,设计用于在用户在文本字段中输入完成后运行一个函数…
$(document).ready(function(e) { var timeout; var delay = 2000; // 2 seconds $('.text-input').keyup(function(e) { $('#status').html("User started typing!"); if(timeout) { clearTimeout(timeout); } timeout = setTimeout(function() { myFunction(); }, delay); }); function myFunction() { $('#status').html("Executing function for user!"); } }); <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> Status: <span id="status">Default Status</span><br> <textarea name="text-input" class="text-input"></textarea>
如果有人喜欢延迟相同的函数,并且没有外部变量,他可以使用下一个脚本:
function MyFunction() {
//Delaying the function execute
if (this.timer) {
window.clearTimeout(this.timer);
}
this.timer = window.setTimeout(function() {
//Execute the function code here...
}, 500);
}