添加基于 URL 的活动导航类

新手上路,请多包涵

我正在尝试将 active 类(即 class="active" )添加到基于页面加载后所在页面的相应菜单列表项。下面是我现在的菜单。我已经尝试了在这方面可以找到的所有代码片段,但没有任何效果。那么,有人可以简单地解释一下在何处以及如何添加 javascript 来定义此任务吗?

 <ul id="nav">
    <li id="navhome"><a href="home.aspx">Home</a></li>
    <li id="navmanage"><a href="manageIS.aspx">Manage</a></li>
    <li id="navdocso"><a href="docs.aspx">Documents</a></li>
    <li id="navadmin"><a href="admin.aspx">Admin Panel</a></li>
    <li id="navpast"><a href="past.aspx">View Past</a></li>
</ul>

这是我在网站管理员的 head 标签中放置的 javascript 示例。我究竟做错了什么?

 $(document).ready(function () {
    $(function () {
        $('li a').click(function (e) {
            e.preventDefault();
            $('a').removeClass('active');
            $(this).addClass('active');
        });
    });
});

原文由 slybitz 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 286
2 个回答

这不起作用的原因是因为 javascript 正在执行,然后页面正在重新加载,这使“活动”类无效。您可能想要做的是:

 $(function(){
    var current = location.pathname;
    $('#nav 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');
        }
    })
})

在某些情况下这是行不通的(多个指向相似的链接),但我认为这对您有用。

原文由 Rob M. 发布,翻译遵循 CC BY-SA 3.0 许可协议

     jQuery(function($) {
     var path = window.location.href; // because the 'href' property of the DOM element is the absolute path
     $('ul a').each(function() {
      if (this.href === path) {
       $(this).addClass('active');
      }
     });
    });
 .active, a.active {
    color: red;
}
a {
    color: #337ab7;
    text-decoration: none;
}
li{
    list-style:none;
}
 <h3>Add Active Navigation Class to Menu Item</h3>

    <ul>
     <li><a href="/">Home</a></li>
     <li><a href="/about/">About</a></li>
    </ul>

<h2><a href="http://www.sweet-web-design.com/examples/active-item/active-class.html">Live Demo</a></h2>

原文由 Figar Ali 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题