$ (this) and this, what's the difference?

Can someone please explain a little what is the difference between the two?

For example, I could do this with "this":

var bar;
button.click(function () {
    if (bar == this) {
        alert('same');
    }
    bar = this;
});

and cannot with $ (that):

var bar;
button.click(function(){
  if(bar == $(this)) {alert('same');}
  bar = $(this);
});
+3
source share
4 answers

The second example does not work, because every time you use a function $(this), it returns a unique jQuery object :

var a = document.createElement('a');
var b = $(a);
var c = $(a);

Now b and c are unique instances of jQuery.

console.log(c == b) // prints false

When using jQuery click events, thisthis is event.currentTarget in the callback, which is the HTML element that binds the click:

button.click(function(e) {
    console.log (e.currentTarget == this) // prints true
})

$(this) jQuery(this) - , HTML, jQuery, jQuery.

+7

this - Javascript.

$(this) - jQuery . jQuery.

+7

$(this) jQuery, this. this - HTMLElement, , .

+1

, .

(. Google "jquery this" )

+1

Source: https://habr.com/ru/post/1733495/


All Articles