jQuery - Active Link and Parent Relationship

2019-06-01 20:28发布

问题:

I am working on a navigation for a site and need some guidance on dynamically adding a class to the active link. In addition, once that link is established and I need to reference back to the parent and have it "show".

This is what I am working with. The navigation is accordion style but does not use the Accordion UI.

<ul id="menu3">
    <li><a href="{site_url}">Home</a></li>
    <li><a class="drop" href="#">Information</a>
        <ul>
            <li><a href="{site_url}information/audio">Audio</a></li>
            <li><a href="{site_url}information/video">Video</a></li>
            <li><a href="{site_url}information/presentations">Presentations</a></li>
        </ul>
    </li>
    <li><a class="drop" href="#">Clinics</a>
        <ul>
            <li><a href="{site_url}clinics/one">Office 1</a></li>
            <li><a href="{site_url}clinics/two">Office 2</a></li>
        </ul>
    </li>
    <li><a href="{site_url}forms/">Forms</a></li>
    <li><a href="{site_url}success_stories/index">Success Stories</a></li>

Then I have a bit of jQuery to initially hide the submenu items:

$(function(){
$('ul#menu3 ul').hide();                
$('ul#menu3 > li > a.drop').click(function(){
$(this).parent().children('ul').toggle("slow");
   return false;
});

So far so good. Everything works.

Now I would like to dynamically highlight the active link and I tried using:

var path = location.pathname.substring(1);
if ( path )
$('ul#menu3 a[href$="' + path + '"]').attr('class', 'selected');

but it doesn't seem to be enough to add the correct class.

The last thing I need to do is to have the navigation open to the active group. For example if Audio is the current page, the Information section of the navigation accordion would be open to show the active link.

I would really appreciate some help on this. Thanks.

回答1:

The following just works fine for me. Also your add "selected" code works as expected. Comments provided inline. If question remain open... comment/ask.

$(function() {
    var pathname = location.pathname;
    var highlight;
    //highlight home
    if(pathname == "/")
        highlight = $('ul#menu3 > li:first > a:first');
    else {
        var path = pathname.substring(1);
        if (path)
            highlight = $('ul#menu3 a[href$="' + path + '"]');
    }
    highlight.attr('class', 'selected');

    // hide 2nd, 3rd, ... level menus
    $('ul#menu3 ul').hide();

    // show child menu on click
    $('ul#menu3 > li > a.drop').click(function() {
        //minor improvement
        $(this).siblings('ul').toggle("slow");
        return false;
    });

    //open to current group (highlighted link) by show all parent ul's
    $('a.selected').parents("ul").show();

    //if you only have a 2 level deep navigation you could
    //use this instead
    //$('a.selected').parents("ul").eq(0).show();
});