简体   繁体   中英

Jquery - How to add active class to entire navigation menu path?

I have a menu with 3 levels, and I would like to use a class for the first active li and a second class for all other subsequent li. When I click on a selection the level 3 to remain active the whole path (level 1, level 2, level 3). If I click on a selection on level 2 to remain active up to level 2.

I have the following:

$(document).ready(function(){
    $('.sf-menu li a').each(function(index) {
        if((this.pathname.trim() == window.location.pathname))
            $(this).parent().addClass("selected");
                var next_li = $(this).parent().next();
            $('a', next_li).addClass("selected2");
    });
});

I think I got it this time, It's a bit dirty but It works.

First add classes so you can identify first, second and third level <li> elements. Do it in the foreach , or whatever bucle that makes the menu (or by hand if there's no such bucle):

<ul id="navlist" >
  <li id="home" class="firstLevel">
    <a class="nav" href="home">Home</a>
    <ul class="secondLevel">
        <li class="secondLevel">
            <a class="nav2" href="home">sub-Home1</a>
            <ul>
                <li class="thirdLevel"><a class="nav3" href="home">sub-sub-Home1></a></li>
                <li class="thirdLevel"><a class="nav3" href="home">sub-sub-Home1></a></li>
            </ul>
        </li> 
        <li><a class="nav2" href="home">sub-Home2</a></li> 
    </ul>
  </li>

  <li id="about" class="firstLevel">
    <a class="nav" href="about-us">About Us</a>
  </li>
</ul>

Then use jQuery closest . It traverses up the DOM tree and matches the closest item, you can pass a selector (the firstLevel or secondLevel classes we just created):

$('#navlist a').on('click', function (e) {
            e.preventDefault(); //prevent the link from being followed
            $('#navlist a').removeClass('selected');
            $('#navlist a').removeClass('selected2');
            $(this).closest('.secondLevel').children('a').addClass('selected2');
            $(this).closest('.firstLevel').children('a').addClass('selected2');
            $(this).addClass('selected');
        });

Then you add !important to the selected class (so when there's a colision like in the About Us link selected is the class that is applied). This is the dirtiest part.

Check a working fiddle: https://jsfiddle.net/4r5vg/661/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM