When to use $(this) and isn't that slower?
In jQuery we can do like...
$('.button').click( function() {
$(this).hide();
} );
But we can do like this too, of course:
$('.button').click( function() {
$('.button').hide();
} );
What're advantages of using this? Isn't that slower?
I think the answer for this question will be something like...
There are situations when only way is to use this.
Show me example of that situation then! :)
Which 开发者_如何学Goshould I use primary (if both would work)?
You should use
this
if all you want to do is accessing DOM properties (that are implemented by all browsers, there are some).For example:
this.href
(<a>
),this.src
(<img>
),this.id
(all elements (if set)), etc. This is the fastet way as you don't make a function call to jQuery.You should use
$(this)
if you want to apply jQuery functions to the DOM element.You should avoid using
$(selector)
if you already have a reference to that element. Searching the DOM again is way slower.
You can see in line 92 of the source code that there is not much happening when you pass an HTML element.
Also note that $(this).hide()
and $('.button').hide();
are not equivalent. The first will only hide the clicked element, while the second will hide all .button
elements.
this
refers to the actual clicked element where as $('.button').hide();
would hide all elements with the class button
.
They don't work the same and even if they would, this
would actually be faster since $('.button')
has to find the element again from the whole document.
Using $(this)
is slower than using this
directly, but it is not slower (in general) than hitting the DOM again by using $('.button')
inside your handler.
The key difference between the two is that this
is always going to be one element. $('.button')
could be any number of elements. So which you use depends on what you want to hide.
So if you want to work with the clicked button only:
// Fastest if using DOM methods / properties
this.SOME_DOM_METHOD();
// Fastest if using some jQuery method that can take a DOM element
jQuery.method_that_takes_an_element(this, additional, args);
// Fastest if using a jQuery method that cannot take a DOM element
jQuery(this).SOME_JQUERY_METHOD();
If you want to work with all of elements with a class of button
:
// Fastest if no new .button elements will be created
var buttons = $('.button');
buttons.click(function() {
buttons.hide();
});
// Slow but I think necessary if new .button elements will be created
$('.some_container').delegate('.button', 'click', function() {
$('.button').hide();
});
in first case you hide only one current element. in second case you just hide everything with class button
this
points to an already existing object, you don't need to evaluate an expression and find the element again, which takes more time and memory.
精彩评论