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

Add Active Navigation Class Based on Child Page URL

本文关键字:活动 导航 URL 添加      更新时间:2023-09-26

我有一个基本的侧菜单结构,它是根据帖子主题动态生成的。使用下面的代码,我能够在查看单个主题页面时单独突出显示活动链接。然而,在列出所有主题的主页或索引页上,侧边导航中的每个锚元素都被赋予了一个'active'类。如何防止索引页sidenav锚接收"活动"类,同时在各个主题页面上保留"活动"类?

提前感谢任何可以提供一些见解的人…

侧导航结构:

<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:

$(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');
        }
    })
})

使用上述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>

使用上述JS在主题索引页(/customer)上的当前输出

<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>

尝试将最后一个键添加到当前可能是协议问题,这样您可以始终确保

$(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');
        }
    });
});