【问题标题】:What's the difference between '$(this)' and 'this'?'$(this)' 和 'this' 有什么区别?
【发布时间】:2023-12-11 23:14:01
【问题描述】:

我目前正在学习本教程:Getting Started with jQuery

以下两个例子:

$("#orderedlist").find("li").each(function (i) {
    $(this).append(" BAM! " + i);
});
$("#reset").click(function () {
    $("form").each(function () {
        this.reset();
    });
});

请注意,在第一个示例中,我们使用$(this) 在每个li 元素内附加一些文本。在第二个示例中,我们在重置表单时直接使用this

$(this) 似乎比this 更常用。

我的猜测是在第一个示例中,$() 将每个 li 元素转换为一个 jQuery 对象,该对象可以理解 append() 函数,而在第二个示例中,reset() 可以直接在表单上调用。

基本上,我们需要 $() 来处理特殊的 jQuery-only 函数。

这是正确的吗?

【问题讨论】:

  • @Reigel,为什么要保护它? OP提问并猜出正确答案。
  • @Reigel:我想我应该在 meta 中问这个问题,但如果这就是保护所需的全部内容,那么不应该所有问题都受到 protected

标签: javascript jquery this


【解决方案1】:

是的,当您使用 jQuery 时,您只需要 $()。如果你想要 jQuery 的帮助来做 DOM 事情,请记住这一点。

$(this)[0] === this

基本上每次返回一组元素时,jQuery 都会将其转换为jQuery object。如果你知道你只有一个结果,它将在第一个元素中。

$("#myDiv")[0] === document.getElementById("myDiv");

等等……

【讨论】:

  • 如果$(this)[0] 始终相同,是否有理由使用this
  • @Jay 如果您喜欢输入 long 而不是简单地使用“this”,那么可以。 $() 是 jQuery 构造函数。 “'this' 是对调用的 DOM 元素的引用。所以基本上,在 $(this) 中,您只是将 $() 中的 this 作为参数传递,以便您可以调用 jQuery 方法和函数”。
  • @jay - 没有充分的理由使用$(this)[0] 我只是用它来说明这个概念。 :) 我确实使用$("#myDiv")[0] 而不是document.getElementById("myDiv")
【解决方案2】:

$() 是 jQuery 构造函数。

this 是对调用的 DOM 元素的引用。

所以基本上,在$(this) 中,您只是将$() 中的this 作为参数传递,以便您可以调用jQuery 方法和函数。

【讨论】:

    【解决方案3】:

    是的,jQuery 函数需要$(this),但是当你想访问不使用 jQuery 的元素的基本 javascript 方法时,你可以使用 this

    【讨论】:

      【解决方案4】:

      使用jQuery时,建议通常使用$(this)。但如果你知道(你应该学习并知道)其中的区别,有时只使用this 会更方便快捷。例如:

      $(".myCheckboxes").change(function(){ 
          if(this.checked) 
             alert("checked"); 
      });
      

      更简单更纯粹
      $(".myCheckboxes").change(function(){ 
            if($(this).is(":checked")) 
               alert("checked"); 
      });
      

      【讨论】:

      • 我喜欢这个例子。谢谢!
      【解决方案5】:

      this 是元素,$(this) 是使用该元素构造的 jQuery 对象

      $(".class").each(function(){
       //the iterations current html element 
       //the classic JavaScript API is exposed here (such as .innerHTML and .appendChild)
       var HTMLElement = this;
      
       //the current HTML element is passed to the jQuery constructor
       //the jQuery API is exposed here (such as .html() and .append())
       var jQueryObject = $(this);
      });
      

      深入了解

      thisMDN 包含在执行上下文中

      范围是指当前的Execution ContextECMA。为了理解this,理解执行上下文在 JavaScript 中的运行方式很重要。

      执行上下文绑定 this

      当控制进入执行上下文(代码在该范围内执行)时,变量的环境被设置(词法和变量环境 - 本质上,这为变量设置了一个已经可以访问的区域,以及一个用于本地的区域要存储的变量),并发生this的绑定。

      jQuery 绑定 this

      执行上下文形成一个逻辑堆栈。结果是堆栈中更深的上下文可以访问以前的变量,但它们的绑定可能已被更改。 每次 jQuery 调用回调函数时,它都会使用 applyMDN 更改 this 绑定

      callback.apply( obj[ i ] )//where obj[i] is the current element
      

      调用apply的结果是在jQuery回调函数内部,this指的是当前被回调函数使用的元素

      例如.each中,常用的回调函数允许.each(function(index,element){/*scope*/})。在那个范围内,this == element 是真的。

      jQuery 回调使用 apply 函数将被调用的函数与当前元素绑定。该元素来自 jQuery 对象的元素数组。每个构造的 jQuery 对象都包含一个元素数组,这些元素与用于实例化 jQuery 对象的 selectorjQuery API 匹配。

      $(selector) 调用 jQuery 函数(请记住,$ 是对 jQuery 的引用,代码:window.jQuery = window.$ = jQuery;)。在内部,jQuery 函数实例化了一个函数对象。所以虽然它可能不是很明显,但在内部使用$() 会使用new jQuery()。这个 jQuery 对象的部分构造是查找选择器的所有匹配项。构造函数还将接受 html 字符串和元素当您将this 传递给 jQuery 构造函数时,您将传递用于构造 jQuery 对象的当前元素。然后,jQuery 对象包含与选择器匹配的 DOM 元素的类数组结构(或者在 this 的情况下仅包含单个元素)。

      一旦构造了 jQuery 对象,jQuery API 现在就暴露出来了。当调用 jQuery api 函数时,它将在内部迭代这个类似数组的结构。对于数组中的每一项,它都会调用 api 的回调函数,将回调的this 绑定到当前元素。这个调用可以在上面的代码 sn-p 中看到,其中obj 是类数组结构,i 是用于当前元素在数组中的位置的迭代器。

      【讨论】:

        【解决方案6】:

        是的,通过使用$(this),您为对象启用了 jQuery 功能。只要使用this,它就只有通用的Javascript功能。

        【讨论】:

          【解决方案7】:

          this引用了一个javascript对象,$(this)用来封装jQuery。

          示例 =>

          // Getting Name and modify css property of dom object through jQuery
          var name = $(this).attr('name');
          $(this).css('background-color','white')
          
          // Getting form object and its data and work on..
          this = document.getElementsByName("new_photo")[0]
          formData = new FormData(this)
          
          // Calling blur method on find input field with help of both as below
          $(this).find('input[type=text]')[0].blur()
          
          //Above is equivalent to
          this = $(this).find('input[type=text]')[0]
          this.blur()
          
          //Find value of a text field with id "index-number"
          this = document.getElementById("index-number");
          this.value
          
          or 
          
          this = $('#index-number');
          $(this).val(); // Equivalent to $('#index-number').val()
          $(this).css('color','#000000')
          

          【讨论】: