📜  jQuery 中 $(this) 和 'this' 之间的区别

📅  最后修改于: 2022-05-13 01:55:56.181000             🧑  作者: Mango

jQuery 中 $(this) 和 'this' 之间的区别

在本文中,我们将了解两者之间的区别 这个 $(this)在 jQuery 中。

this 关键字在 JavaScript 中, this关键字用于引用它所属的对象。 this存储的值是 JavaScript 程序的当前执行上下文。因此,当在函数内部使用时, this的值将根据该函数的定义方式、调用方式和默认执行上下文而改变。

示例 1:我们将在一个对象方法中使用this 指对象的所有者。

HTML


  

    
    
  

  

  
    

The object's value for name:

       

          


HTML


  

    
    

  

    

         Click this to change color.
    

             


HTML


  

    
    

  

    
        

Click to change color

    
       

GeekForGeeks

          


HTML


  

    
    
      

  

    

        Hello     

          


HTML


  

    
        

  

    

        Hello     

          


输出:

The object's value for name:

hrithik



示例 2:我们将在事件处理程序上使用this关键字,它指的是在其上调用事件的元素。

HTML



  

    
    

  

    

         Click this to change color.
    

             

输出:

$(this):它也指向它所属的对象。基本上,两者是相同的。但是当这个关键字在$() 中使用时,它就变成了一个 jQuery 对象,现在我们可以在这个方法上使用 jQuery 的所有属性。

例子:

HTML



  

    
    

  

    
        

Click to change color

    
       

GeekForGeeks

          

输出:

这和 $(this) 之间的区别



this关键字是对调用 DOM 元素的引用。我们可以在其上调用所有 DOM 方法。 $()是一个 jQuery 构造函数,在$(this) 中,我们只是将作为参数传递,以便我们可以使用 jQuery函数和方法。

示例 1:以下代码不起作用,因为我们正在对 DOM 元素调用 jQuery 方法。请参阅输出以获得更好的理解。隐藏不会发生。

HTML



  

    
    
      

  

    

        Hello     

          

输出:

例2:此代码工作正常,因为我们已经实现了这个到$(),现在它成为一个jQuery对象。

HTML



  

    
        

  

    

        Hello     

          

输出:

这和 $(this) 之间的区别

                                                     this                                                            

                                       $(this)                   
It refers to DOM elementsIt also refers to DOM elements.
this is used in a native way.this is put in $(), it becomes a jQuery object.
We can call all DOM methods on it but not jQuery methods.We can call all jQuery methods and functions on it but not DOM methods.
this has only generic JavaScript functionality.By using $(this), you enabled jQuery functionality for the object.