首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >基于子页面URL添加活动导航类

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

Stack Overflow用户
提问于 2015-08-13 19:14:39
回答 1查看 3.1K关注 0票数 0

我有一个基本的侧菜单结构,它是基于post主题动态生成的。使用code below,在查看单个主题页时,我能够按预期的方式单独突出显示活动链接。但是,在列出所有主题的主页面或索引页上,侧导航中的每个锚元素都会被赋予一个“活动”类。如何防止索引页sidenav锚点接收“活动”类,同时在单个主题页上保留“活动”类?

预先感谢任何能提供一些见解的人..。

侧导航结构:

代码语言:javascript
复制
<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');
        }
    })
})

当前在个人主题页上使用上述JS的输出

代码语言:javascript
复制
<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的当前输出

代码语言:javascript
复制
<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>
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-13 19:29:25

试试看,添加到当前的最后一个密钥可能是一个协议问题,这样您就可以始终确定

代码语言:javascript
复制
$(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');
        }
    });
});
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/31996621

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档