$(this) and this, what difference?
Could someone please explain a bit, what difference between them?
For example I could do that wit开发者_StackOverflow社区h "that":
var bar;
button.click(function () {
if (bar == this) {
alert('same');
}
bar = this;
});
and couldn't with $(that):
var bar;
button.click(function(){
if(bar == $(this)) {alert('same');}
bar = $(this);
});
Your second example doesnt work, because every time you use the $(this)
function, it returns an unique jQuery Object:
var a = document.createElement('a');
var b = $(a);
var c = $(a);
Now, b and c are both unique jQuery instances.
console.log(c == b) // prints false
When using jQuery click events, this
is the event.currentTarget in the callback, which is the HTML element that bound the click:
button.click(function(e) {
console.log (e.currentTarget == this) // prints true
})
$(this)
or jQuery(this)
is a function that returns the HTML element wrapped in a unique jQuery Object, and contains all jQuery prototypes.
this
is the plain Javascript object.
$(this)
is a jQuery wrapped element. You are allowed to call jQuery methods with it.
$(this)
creates a jQuery object containing this
. this
is the HTMLElement
representing the button which was clicked.
Here's quite a good page that explains it in detail with examples.
(Note: It was also the first google result for "jquery this")
精彩评论