jQuery selector special selector this

 

 Many people who are new to jQuery are confused about the difference between $(this) and this, so what is the difference between the two?

 

this is a keyword in JavaScript that refers to the current context object, which is simply the owner of the method/property.

 

In the following example, imooc is an object with a name attribute and a getName method. In getName, this points to the object imooc to which it belongs.

var imooc = {
    name:"MOOC",
    getName:function(){
        //this, is the imooc object
        return this.name;
    }
}
imooc.getName(); //MOOC
 

Of course, this is dynamic in JavaScript, which means that this context object can be changed dynamically (through call, apply, etc.). For details, you can refer to the relevant information.

Similarly in the DOM this points to the html element object, because this is a reference to the DOM element itself

If you bind an event to a P element on the page:

p.addEventListener('click',function(){
    //this === p
    //The following two modifications are equivalent
    this.style.color = "red";
    p.style.color = "red";
},false);

 

In the event callback bound by addEventListener, this points to the current dom object, so to modify the style of such an object again, you only need to get the reference through this

this.style.color = "red"

But this kind of operation is actually very inconvenient. It involves a lot of style compatibility. If it is processed through jQuery, it will be much simpler. We only need to process this into a jQuery object.

Replacing it with jQuery:

$('p').click(function(){
    // Convert the p element to a jQuery object
    var $this= $(this)
    $this.css('color','red')
})

 

By passing the reference this of the current element object into the $() method, and processing this into a jQuery object, we can use the shortcut method provided by jQuery to directly process the style

overall:

this indicates that the current context object is an html object, and the properties and methods owned by the html object can be called.

The context object represented by $(this) is a jQuery context object, which can call jQuery methods and property values.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326927355&siteId=291194637