Collapsible menu javascript problem
I am struggling with a collapsible vertical menu. The first part of the script below works, so that the upper UL display its sibling LIs, while the other ULs keep their sibling LIs hidden. My difficult task (to me at least) is to make the parent UL to the active link keep its sibling LIs visible. This is what I tried in the lower part of the script. My a-links some times get a trailing hash (#) which I want to remove in order to compare i to the active URL. This is done through the trimHash(string)-function--which works when tested on a simple string, but not in this script. Any good advice out there?
$(document).ready(function() {
// Collapse everything but the first menu:
$(".mainmenu > li > a").not(":first").find("+ ul").slideUp(1);
// Expand or collapse:
$(".mainmenu > li > a").click(function() {
$(this).find("+ ul").slideTo开发者_开发问答ggle("fast");
});
$(".mainmenu li").each(function () {
var li = $(this);
var a = rtrimHash(li[0].firstChild);
if (a.href == location.href) {
$(this).find("+ ul").slideDown(1);
}
});
I ended up with this solution. As it is a Wordpress site, while stepping through the menu items in the menu I could check if each link is active by comparing the link to the active post, and insert the class "current" to these menu items:
echo '<li class="child';
if ( $menuPost->ID == $post->ID ) { echo ' current'; }
And then use jQuery to find all instances of the li "current" class, and trigger the parent ul's to slideDown:
$(document).ready(function() {
// Collapse everything:
$("li.cat").find("+ ul").slideUp(1);
// Collapse everything but the first menu:
//$("li.cat").not(":first").find("+ ul").slideUp(1);
// Expand or collapse:
$("li.cat").click(function() {
$(this).find("+ ul").slideToggle("fast");
});
$("li.current").parent().slideDown(1);
});
Sorry I didn't solve this through javascript as I intended, but I achieved what I wanted.
精彩评论