When writing JavaScript in jQuery is it best to do:
$('.select').click(function(e){
$(this).something();
//Or
this.something();
});
Is there any difference? What are the advantages or disadvantages of either way?
When writing JavaScript in jQuery is it best to do:
$('.select').click(function(e){
$(this).something();
//Or
this.something();
});
Is there any difference? What are the advantages or disadvantages of either way?
$(this)
is a jQuery object and this
is a pure DOM Element object. See this example:
$(".test").click(function(){
alert($(this).text());
//and
alert(this.text()); // error no method
});
They're completely different. Neither is "better" and you cannot compare their advantages and disadvantages. One is a jQuery object, one is a raw HTML element.
The other answers are correct, however I would like to add that this
within the context of $.fn.function
also refers to the jQuery object.
For example:
$.fn.function = function() {
this.width();
}
In the callback scope of jquery of an event handler this
is the pure element.
$(this)
would wrap it again into a jquery instance
So the result is very different and it simply depends on what you need...
this
and $(this)
will give different results as $(this)
is jQuery instance and this
is HTML element.