我希望和输入的事件发射器在输入输入时稍微延迟(冷却),比如1秒,所以输入一个单词会多次触发,但在最后一次击键后只有1秒
我找到了这段代码
$.fn.changeOrDelayedKey = function(fn, iKeyDelay, sKeyEvent) {
var iTimeoutId,
oEventData;
// second signature used, update the variables
if (!$.isFunction(fn)) {
oEventData = arguments[0];
fn = arguments[1];
iKeyDelay = arguments[2];
sKeyEvent = arguments[3];
}
if (!iKeyDelay || 0 > iKeyDelay) {
iKeyDelay = 500;
}
if (!sKeyEvent || !this[sKeyEvent]) {
sKeyEvent = 'keydown';
}
// non-delayed event callback, should clear any timeouts, then
// call the original callback function
function fnExecCallback() {
clearTimeout(iTimeoutId);
fn.apply(this, arguments);
}
// delayed event callback, should call the non-delayed callback
// after a short interval
function fnDelayCallback() {
var that = this,
args = arguments;
clearTimeout(iTimeoutId);
iTimeoutId = setTimeout(function() {
fnExecCallback.apply(that, args);
}, iKeyDelay);
}
if (oEventData) {
this.change(oEventData, fnExecCallback);
this[sKeyEvent](oEventData, fnDelayCallback);
}
else {
this.change(fnExecCallback);
this[sKeyEvent](fnDelayCallback);
}
return this;
};
这是什么类型的,但它也会在change
上触发,这意味着如果我写了一些东西而没有移动焦点后说5秒钟,那么当我最后,事件再次激发,它不应该。所以我只希望事件发生在keyup
事件上。
如果有人能够解释该方法是如何工作的,以及我如何修改它以适合我的用例,那将非常感激
答案 0 :(得分:1)
如果我了解您的使用情况,您可以使用setTimeout()
和clearTimeout()
:
$(function() {
var timeOut = 0;
$("#test")
.keyup(function() {
// cancel looking, the user typed another character
clearTimeout(timeOut);
// set a timeout, when user doesn't type another key
// within half a second the function is called
timeOut = setTimeout(function() {
stopptedTyping();
}, 500); // change time as needed
});
});
function stopptedTyping(){
alert('user stopped typing');
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test"/>