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

标签 javascript jquery

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

相关文章:

javascript - 获取 HTML5 文档中 SVG 内联元素的屏幕位置

jquery "one animation after another"

javascript - 如何提高 Jquery 自动完成的性能

javascript - 我怎样才能修复动画速度?

javascript - AngularJS - 在数组中单步执行数组

Javascript:如何将英语格式的 float 转换为西类牙语格式的 float ?

php - 验证此图像验证码。 Jquery PHP 和 JavaScript

javascript - Jquery:JSON 解析总是出现意外的字符错误

javascript - 是否可以使用 CSS 或 Javascript 隐藏网页中的光标?

javascript - 如何在 Reactjs 中更改 CKEditor 5 的配置