I am writing some code to turn a multi level UL into an accordion:
$(document).ready(function () {
$('.s4-ql li ul').each(function (index) {
$(this).hide();
});
$('.s4-ql ul li ul').each(function (index) {
var length = 0;
length = $(this).children().length;
var CurrentItem = $(this).parent().find('a:first');
CurrentItem.find('.menu-item-text').append('<span style=\'float:right;font-size:0.8em;\'>(' + length + ')</span>');
});
$('.s4-ql ul li').hover(
function () {
$(this).find('a:first').next().slideToggle('normal');
},
function () {
$(this).find('a:first').next().slideToggle('normal');
}
);
});
Can anyone tell me whether I am being relatively efficient or whether there is anywhere that I can "trim the fat", so to speak? The code also counts the number of children and displays that number on the main parent.
-
1\$\begingroup\$ Also, speaking of "trimming the fat", please don't write tags in titles and signatures in questions. \$\endgroup\$Lightness Races in Orbit– Lightness Races in Orbit2011年12月15日 15:13:58 +00:00Commented Dec 15, 2011 at 15:13
-
\$\begingroup\$ What do you mean Tom? sorry? - As for code review..thx for that link, was not aware of it. \$\endgroup\$user257503– user2575032011年12月15日 15:18:56 +00:00Commented Dec 15, 2011 at 15:18
-
\$\begingroup\$ @user257503: I mean, please don't write tags in titles (like "jQuery: "), and signatures/thanks are not required (and will be edited out) as you're writing a question not an email! ta [not the same for comments :P] \$\endgroup\$Lightness Races in Orbit– Lightness Races in Orbit2011年12月15日 15:23:54 +00:00Commented Dec 15, 2011 at 15:23
2 Answers 2
It'll be good if you can provide your HTML markup. Without it I can do this:
jQuery(function($) {
$('.s4-ql li ul').hide();
$('.s4-ql ul li').hover(function() {
$(this).find('a:first').next().slideToggle();
}, function() {
$(this).find('a:first').next().slideToggle();
}).find('ul').each(function(index) {
var $this = $(this);
$this.parent().find('a:first .menu-item-text').append(['<span style=\'float:right;font-size:0.8em;\'>(', $this.children().length, ')</span>'].join(''));
});;
});
All jQuery mutation methods operate on every element in the set.
You can just write $('.s4-ql li ul').hide()
; you don't need .each
.
Also, you should just write var length = $(this).children().length;
in one line.