What's the difference between $(this) and this

2019-01-18 10:03发布

问题:

What's the difference between $(this) and this in jQuery, and why do they sometimes give the same result and other times behave differently?

回答1:

$(this) wraps this with the jQuery functionality.

For example, this code would fail:

$('.someDiv').onClick(function(){
    // this refers to the DOM element so the following line would fail
    this.fadeOut(100);
});

So we wrap this in jQuery:

$('.someDiv').onClick(function(){
    // wrap this in jQuery so we can use jQuery fadeOut
    $(this).fadeOut(100);
});


回答2:

$(this) decorates whatever object this points to with the jQuery functions. The typical use case is for this to reference a DOM element (say, a <div>). Then, writing $(this) allows you to use all the jQuery API functions on that <div>.

If this already refers to a jQuery object - usually a jQuery-decorated DOM object - then calling $(this) will have no effect because it's already decorated.



回答3:

If in your current context if the this is not a jQuery object, you can make it a jQuery element by wrapping it around $(). When your element already is a result of jQuery expression, the this in that case is already a jQuery object. So in that case they both work similarly



回答4:

for you to understand a little bit better, get yourself a debugger of somekind such as google chrome and do this..

$('a').click(function(){
    console.log(this); //DO
    console.log($(this)); //JO
});

this will show you what the difference is :)



回答5:

this is a javascript variable created whenever you are inside a function which is attached to an object. In these cases, this refers to that object.

$(this) returns a jQuery object which you can call jQuery functions on, but will apply only to this.

For example, if you set a click handler for all anchors:

$('a').click(function() {
    console.log(this.href) ;
}) ;

then the this, refers to the anchor, which the click event (function) is attached to.



回答6:

$(this) == this ? interesting.

this must not pass by DOM event.



回答7:

In JavaScript this always refers to the “owner” of the function that is executing. Using $(this) will only wrap the owner so that all the jQuery operations will be extended and available to it.

Consider:

$links = $('#content a');

$links.click(function() {
    link  = this;
    $link = $(this); //jQuery wrapped object.

    alert(link.getAttribute('href'));        
    alert($link.attr('href')); //we can use the attr() function from jQuery
});

They usually give the same results since the owner is the same, only that when wrapped by jQuery it can operate with the jQuery functions.