密钥上的jQuery延迟

时间:2013-08-05 00:11:35

标签: javascript jquery delay keyup

我正在尝试在我自己的代码中实现this answer

$(document).ready(function() {

    $('#qty').delayKeyup(function() {
        var qty = $(this).val();
        $(this).val(Math.round(qty / 10) * 10);
    }, 1000);

});

(function ($) {
    $.fn.delayKeyup = function(callback, ms){
        var timer = 0;
        $(this).keyup(function(){
            clearTimeout (timer);
            timer = setTimeout(callback, ms);
        });
        return $(this);
    };
})(jQuery);

但输入值没有变化。如果我删除delayKeyup函数,更改工作正常,但显然没有延迟。我错过了什么?

1 个答案:

答案 0 :(得分:4)

您需要确保使用正确的this值调用处理函数:

    var timer = 0, elem = this;
    $(this).keyup(function(){
        clearTimeout (timer);
        timer = setTimeout(callback.bind(elem), ms);
    });

编写回调以期望this将成为涉及的DOM元素。

此外,确保您的jQuery附加组件方法与良好的jQuery公民一样,这是一种很好的做法。在这种情况下,如果“delayKeyup”的选择器引用多个元素,则应该使用.each()

(function ($) {
    $.fn.delayKeyup = function(callback, ms){
        return this.each(function() { // $(this) not necessary for a jQuery add-on
          var timer = 0, elem = this;
          $(this).keyup(function(){
            clearTimeout (timer);
            timer = setTimeout(callback.bind(elem), ms);
          });
        });
    };
})(jQuery);

并非所有浏览器都支持.bind(),但幸运的是,在这种情况下,有一个非常简单的替代方案可以在任何地方使用:

(function ($) {
    $.fn.delayKeyup = function(callback, ms){
        return this.each(function() {
          var timer = 0, elem = this;
          $(this).keyup(function(){
            clearTimeout (timer);
            timer = setTimeout( function() { callback.call(elem); }, ms);
          });
        });
    };
})(jQuery);
相关问题