简体   繁体   English

jQuery-如何将活动类添加到整个导航菜单路径?

[英]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. 我有一个包含3个级别的菜单,并且我想为第一个活动li使用一个类,并为所有其他后续li使用一个第二类。 When I click on a selection the level 3 to remain active the whole path (level 1, level 2, level 3). 当我单击一个选择时,第3级将在整个路径(第1级,第2级,第3级)上保持活动状态。 If I click on a selection on level 2 to remain active up to level 2. 如果我单击级别2上的选择以保持活动状态直到级别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. 首先添加类,以便您可以识别第一,第二和第三级<li>元素。 Do it in the foreach , or whatever bucle that makes the menu (or by hand if there's no such bucle): foreach或制作菜单的任何气泡中进行操作(或在没有气泡的情况下手动进行):

<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 . 然后使用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): 它遍历DOM树并匹配最接近的项目,您可以传递选择器(我们刚刚创建的firstLevel或secondLevel类):

$('#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). 然后添加!important所选类(所以当有一个像colision在关于我们友情连接选择的是应用类)。 This is the dirtiest part. 这是最脏的部分。

Check a working fiddle: https://jsfiddle.net/4r5vg/661/ 检查工作的小提琴: https//jsfiddle.net/4r5vg/661/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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