了解自定义JQuery事件以及如何轻松修改它

Understanding custom JQuery event and how to modify it sligthly

本文关键字:何轻松 修改 自定义 JQuery 事件 了解      更新时间:2023-09-26

我希望在输入时有一个稍微延迟(冷却)的输入上发生事件发射器,比如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"/>