简体   繁体   English

添加基于子页面URL的活动导航类

[英]Add Active Navigation Class Based on Child Page URL

I have a basic side menu structure which is generated dynamically based on post topics. 我有一个基本的侧边菜单结构,它是根据帖子主题动态生成的。 Using the code below I am able to individually highlight the active link as intended when viewing the individual topic page. 使用以下代码,我可以在查看各个主题页面时按预期突出显示活动链接。 However, on the main or index page that lists all topics, every anchor element in the side nav is given an 'active' class. 但是,在列出所有主题的主页或索引页面上,侧面导航中的每个锚点元素都被赋予一个“活动”类。 How can I prevent the index page sidenav anchors from receiving 'active' classes while retaining the 'active' class on individual topic pages? 如何防止索引页面sidenav锚接收“活动”类,同时在各个主题页面上保留“活动”类?

Thanks in advance to anyone whom can provide some insight... 预先感谢任何能提供一些见识的人...

Side nav structure: 侧面导航结构:

<div class="sidenav">
  <ul>
    <li><a href="//example.com/customer/topic/government">Government</a></li>
    <li><a href="//example.com/customer/topic/hospitality">Hospitality</a></li>
    <li><a href="//example.com/customer/topic/industrial">Industrial</a></li>
  </ul>
</div>

Javascript: Javascript:

$(function(){
    var current = location.pathname;
    $('.sidenav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    })
})

Current output using above JS on individual topic pages : 单个主题页面上使用上述JS的当前输出:

<div class="sidenav">
  <ul>
    <li><a href="//example.com/customer/topic/government">Government</a></li>
    <li><a href="//example.com/customer/topic/hospitality" class="active">Hospitality</a></li>
    <li><a href="//example.com/customer/topic/industrial">Industrial</a></li>
  </ul>
</div>

Current output using above JS on topic index page (/customer) 使用主题索引页面上的上述JS的当前输出(/客户)

<div class="sidenav">
  <ul>
    <li><a href="//example.com/customer/topic/government" class="active">Government</a></li>
    <li><a href="//example.com/customer/topic/hospitality" class="active">Hospitality</a></li>
    <li><a href="//example.com/customer/topic/industrial" class="active">Industrial</a></li>
  </ul>
</div>

Try this added the last key to current might be a protocol issue this way you can be always sure 尝试此操作,以这种方式添加最新密钥到当前可能是协议问题,您可以始终确保

$(function(){
    var current = location.pathname;
    current = current.substring(current.lastIndexOf('/'));
    $('.sidenav li a').each(function(){
        var $this = $(this);
        // if the current path is like this link, make it active
        if($this.attr('href').indexOf(current) !== -1){
            $this.addClass('active');
        }
    });
});

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

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