Optimize code for efficiency + quick question
This is a simple o开发者_运维问答ne for you jQuery gurus here in Stackoverflow.
I have the following jQuery function and I'm wondering if there's a way to optimize the code:
$('.dropdown li').click(function(){
$(this).siblings().find('.active').removeClass('active')
$(this).siblings().find('ul:visible').slideUp();
$(this).toggleClass('hover');
$('ul:first',this).slideToggle();
$('.arrow-down',this).toggleClass('active');
});
--------
Quick question as well:
What is the difference between ('.selector' + this)
and ('.selector', this)
? I hope I typed this right.
As you can see I'm quite new to jQ so I need all the help I can get even if I'm asking stupid questions ^_^
Thanks in advance.
Tips:
1 - Seems you're attaching an event handler to many <li>
elements. Don't do that, use delegate instead
2 - No need to do $(this) all the time, just do var $this = $(this);
and use $this
from now on.
3 - If you're really into speeding this up (I don't see any big performance problems there BTW), drop jQuery and use plain javascript.
"What is the difference between
('.selector' + this)
and('.selector', this)
?"
That will depend on what the value of this
is.
If you're in a handler, then this
willl be the element that invoked the handler. As such, this:
('.selector' + this)
...is pretty much useless, since your selector string will look like:
".selector[object HTMLLIElement]"
...which isn't a valid selector.
But this one is different:
('.selector', this)
It makes this
(your element) the root from which you're performing the query for .selector
.
It is effectively the same as:
$(this).find('.selector');
...and in fact, jQuery just flips it around behind the scenes to that form, so you're better of just using .find()
in the first place since it will be more efficient, and its meaning is a little clearer IMO.
Try this
$('.dropdown li').click(function(){
$(this).toggleClass('hover').find('.active').removeClass('active')
.end().find('ul:visible').slideUp();
$('ul:first',this).slideToggle();
$('.arrow-down',this).toggleClass('active');
});
精彩评论