【问题标题】:Add Active Navigation Class Based on Child Page URL添加基于子页面 URL 的活动导航类
【发布时间】:2015-11-06 21:59:35
【问题描述】:

我有一个基于帖子主题动态生成的基本侧边菜单结构。使用code below,我可以在查看单个主题页面时按预期单独突出显示活动链接。然而,在列出所有主题的主页面或索引页面上,侧导航中的每个锚元素都被赋予一个“活动”类。如何防止索引页面 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>

主题索引页面(/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>

【问题讨论】:

    标签: javascript jquery html url dom


    【解决方案1】:

    试试这个添加了当前的最后一个键可能是一个协议问题,这样你就可以始终确定

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

    【讨论】:

    • 感谢您的帮助!仍然遇到同样的问题,其中 .active 被添加到 /customers 页面上的所有锚点。我想也许我可以使用 lastIndexOf 查找 /customers/topic,但问题仍然存在。各个主题页面上的行为是正确的,因为只有活动类被添加到当前正在查看的锚点。
    猜你喜欢
    • 2013-12-02
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    • 1970-01-01
    • 2015-02-18
    • 2012-04-16
    • 1970-01-01
    • 2018-06-15
    相关资源
    最近更新 更多