javascript jQuery $(this) 内部函数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11969104/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 14:55:17  来源:igfitidea点击:

jQuery $(this) inside function

javascriptjquerythis-pointer

提问by user1324762

I want to pass $(this) to function but I am not sure. There is one similar thread, but I still can not make it working. I hope somebody can help me.

我想将 $(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 );
  });
});

回答by Harmen

You should save a reference to this :

您应该保存对此的引用:

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

Another option is to re-bind thisto the function:

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

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

回答by David Hellsing

You would need to bring the context:

你需要带上上下文:

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

And then

接着

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

But as others posted, saving the context in a local variable might be what you really want. Here is another way to do it:

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

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

回答by 0x499602D2

Keep a reference to $(this)outside the function.

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

 // ...

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

回答by James Kyburz

this changed because of function scope change. You need to store the value using a closure.

由于功能范围的变化,这发生了变化。您需要使用闭包存储该值。

If all you pass is the value you don't need $(this)

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

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

Another way would be

另一种方式是

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