jQuery的键盘暂停捕捉 [英] jquery keyboard pause catch
问题描述
我正在捕获每个键盘调用的键盘事件.
Am catching the keyup events which makes calls for each keyup.
jQuery('#Search').keyup(function() {
});
但是我需要类似的东西,例如当用户连续键入字符并在第5个字符或第n个字符处传递密码时,只有我想触发ajax调用.在这里,我们可以使用超时功能来捕获事件,但是每次按键都会调用超时功能,因此再次发生相同的情况
But i need something like when user continuously types characters and gave a pass at 5th character or in n'th character that time only i want to trigger a ajax call. Here we can use timeout function to catch the event but each keypress will call the timeout function so again the same thing happening
如果用户在暂停后再次开始键入内容,则必须再次触发事件/ajax调用,但只能在特定暂停后进行.
And if user again started typing after a pause then again it will have to trigger a event/ajax call but after a certain pause only.
在这里,我们需要中止先前的事件或ajax调用,因为用户再次开始搜索.
Here we need to abort the previous events or ajax calls since again user started searching.
所以我用.abort();
函数中止了以前的调用.
So i used .abort();
function to abort the previous calls.
是否有更好的方法来在特定时间段内在jquery中捕获事件.请给我建议,
Is there a better way to catch event at after a certain period of time in jquery. Please advice me,
预先感谢
推荐答案
var search = $('#Search'),
search_delay = 100;
search.keyup(function() {
var request = search.data('request');
if(request) { // if request is running - abort it
request.abort();
search.data('request', null);
}
clearTimeout(search.data('timer')); // if timer is running - stop it
search.data('timer', setTimeout(function(){
// add your ajax call here or pass a reference
// to the function that will handle the ajax call
search.data('request', $.ajax(...));
}, search_delay);
});
您可以使用jQ data
API存储对jQuery 1.5中引入的jqXHR对象的引用,以便能够abort
请求和计时器,因此可以使用clearTimeout
You can use jQ data
API to store references to the intrduced in jQuery 1.5 jqXHR object to be able to abort
the request and to the timer so you can stop the timer with clearTimeout
这篇关于jQuery的键盘暂停捕捉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!