javascript - jquery this 和 $(this)

标签 javascript jquery jquery-plugins

这似乎是一个老问题,有很多页面解释了两者之间的区别,但我仍然不完全理解它,因为两者似乎都适合我。我想我明白为什么我不能在嵌套函数中使用 this$(this) 。但为什么这两种带有变量的替代方案都有效呢?我应该使用哪一个才是正确的?

(function($) {
$.fn.helloWorld = function() {
  var $wrap1    = this;
  var $wrap2    = $(this);

  var keys = function(){
     $(document).keyup(function (event) {
        if (event.keyCode === 39) {
           console.log("key pressed");
           event.preventDefault();
           this.fadeOut();            //Does not work
           $(this).fadeOut();         //Does not work      
           $wrap1.fadeOut();          //Does work
           $wrap2.fadeOut();          //Does work
        }
     });
  };
  keys();
}
}(jQuery));

最佳答案

对于 jQuery fn 扩展,this 已经引用了 jQuery 对象,因此 $(this) 本质上是一个 no -操作。

但是在大​​多数情况下,比如事件处理程序,this指的是触发事件的元素,需要使用$(this)来调用jQuery函数就在上面。

关于javascript - jquery this 和 $(this),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23152984/

相关文章:

jquery - easySlider 在 IE7 中不工作

javascript - 输入文本后,innerHTML 文本框不起作用

javascript - 将整个 javascript 库包装在 try catch block 中有哪些缺点?

javascript - 如何使用带标志的语言获取下拉列表当前值?

javascript - 如何访问在 Ajax 回调函数中初始化的变量?

javascript - 添加新事件时在 jQuery weekcalendar 中获取 userId

javascript - (向后/向前)按键时的 DOM 导航

javascript - 如何使用 jQuery 在用户选择的文本行中的 <textarea> 末尾添加图像

javascript - 单击动态生成的表中的一行时,选中其单选按钮

jquery - 如何将 html 表格行传递到 DataTable.net fnAddData