简体   繁体   English

使用内部锚点将类添加到活动菜单项

[英]Add class to active menu items with internal anchors

I have a page with a list of menu items consisting of internal anchors. 我有一个页面,其中包含内部锚点的菜单项列表。 I'm trying to add an .active class to the selected item. 我正在尝试将.active类添加到所选项目。 It seems to work on load but when clicking a new item in that same page it doesn't. 它似乎在加载时起作用,但是在同一页面中单击新项目时却没有。

When clicking a new menu item, I would like to remove all other active classes and add this class to the clicked item. 单击新菜单项时,我想删除所有其他活动类并将该类添加到单击的项中。

Sounds pretty simple, but I can't make it work. 听起来很简单,但我无法使其正常工作。 I created this Fiddle , but it doesn't show the issue correctly, since I can't add hashes to the url. 我创建了此Fiddle ,但由于无法将哈希添加到网址中,因此无法正确显示问题。

However, maybe someone can point me in the right direction. 但是,也许有人可以指出正确的方向。

JS: JS:

function setActiveLinks() {
  var current = location.pathname;
  $('.bs-docs-sidenav li a').each(function() {
    var $this = $(this);
    // Get hash value
    var $hash = location.href.substr(location.href.indexOf('#') + 1);
    if ($this.attr('href') == '#' + $hash) {
      $this.parent().addClass('active');
    }
  })
}

setActiveLinks();

$('#leftmenu li a').click(function() {
$('#leftmenu li').removeClass('active');
  setActiveLinks();
});

HTML: HTML:

<ul class="nav bs-docs-sidenav">
  <li>
    <a href="#download">Download</a>
  </li>
  <li class="active">
    <a href="#whats-included">What's included</a>
    <ul class="nav">
      <li class="active"><a href="#whats-included-precompiled">Precompiled</a></li>
      <li><a href="#whats-included-source">Source code</a></li>
    </ul>
  </li>
  <li>
    <a href="#grunt">Compiling CSS and JavaScript</a>
    <ul class="nav">
      <li><a href="#grunt-installing">Installing Grunt</a></li>
      <li><a href="#grunt-commands">Available Grunt commands</a></li>
      <li><a href="#grunt-troubleshooting">Troubleshooting</a></li>
    </ul>
  </li>
</ul>

Thanks. 谢谢。 :-) :-)

You have wrong selector to bind click event on anchor element. 您有错误的选择器来绑定锚元素上的click事件。 also you don't need to call setActiveLinks() function(which sets class based on href) here. 您也不需要在这里调用setActiveLinks()函数(该函数根据href设置类)。

You can use context of clicked anchor element to traverse to parent li and add class active in it: 您可以使用单击的锚元素的上下文遍历到父级li并在其中添加活动类:

var $navLIs = $('.nav li')
$navLIs.find('a').click(function() {
  $navLIs.removeClass('active');
  $(this).parent().addClass('active');
});

Working Demo 工作演示

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

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