gpt4 book ai didi

javascript - 了解自定义 JQuery 事件以及如何对其进行稍微修改

转载 作者:行者123 更新时间:2023-12-03 10:52:12 25 4
gpt4 key购买 nike

我希望输入上的事件发射器在输入输入时有轻微的延迟(冷却),例如 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 事件上。

如果有人可以解释该方法是如何工作的,以及我如何修改它以适合我的用例,我将不胜感激

最佳答案

如果我了解您的用法,您可以使用 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"/>

关于javascript - 了解自定义 JQuery 事件以及如何对其进行稍微修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28392023/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com