jQuery $(this) inside function



我想传递$(this)来运行,但我不确定。有一个类似的线程,但我仍然无法使其工作。我希望有人可以帮助我。

$(document).ready(function() {
  var delay = (function(){
    var timer = 0;
    return function(callback, ms){
      clearTimeout (timer);
      timer = setTimeout(callback, ms);
    };
  })();
  $('input').keyup(function() {
      delay(function(){
        alert($(this).val());
      }, 1000 );
  });
});

你应该保存一个引用:

$('input').keyup(function() {
    var $this = $(this);
    delay(function(){
      alert($this.val());
    }, 1000 );
});

另一种选择是将this重新绑定到函数:

  $('input').keyup(function() {
      delay(function(){
        alert($(this).val());
      }.bind(this), 1000 );
  });

您需要提供上下文:

return function(callback, ms, context){
  clearTimeout (timer);
  timer = setTimeout(function() {
      callback.call(context);
   }, ms);
};

然后

delay(function() {
    alert($(this).val());
}, 1000, this );

但正如其他人发布的那样,将上下文保存在局部变量中可能是您真正想要的。这是另一种方法:

$('input').keyup(function() {
  delay((function(self) {
    return function() {
      alert($(self).val());
    };
  }(this)), 1000);
});

保留对函数外部$(this)的引用。

 // ...
    $('input').keyup(function() {
        var $this = $(this);
        delay(function() {
            alert( $this.val() );
        }, 1000)
    });

由于函数作用域的变化,这发生了变化。您需要使用闭包存储值。

如果您传递的只是不需要的值 $(this)

$('input').keyup(function() {
  var val = this.value;
  delay(function(){
    alert(val);
  }, 1000 );
});

另一种方式是

$('input').keyup(function() {
  delay((function(val){
    return function() {
      alert(val);
    };
  }(this.value)), 1000 );
});

最新更新