1

我正在尝试在我自己的代码中实现这个答案:

$(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 函数,则更改工作正常,但显然不是延迟。我错过了什么?

4

1 回答 1

4

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

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

您的回调被写入期望这this将是所涉及的 DOM 元素。

此外,确保您的 jQuery 附加方法表现得像优秀的 jQuery 公民是一个很好的做法。在这种情况下,您应该使用.each()“delayKeyup”选择器引用多个元素的情况:

(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);
于 2013-08-05T00:13:21.047 回答