提问者:小点点

在子页上向父nav添加活动类


当用户在基于URL的子页面中时,我需要突出显示父nav项。

用户当前在foo1-child页面上,而父级是foo1,因此我需要将活动类添加到foo1:http://Foo.com/foo1/foo1-child.html

<ul class="main-nav">
  <li><a href="/foo.com/foo1.html">Foo 1</a></li>
  <li><a href="/foo.com/foo5.html">Foo 5</a></li>
</ul>

在nav中添加活动类没有问题,因为我只是比较.nav li a中的每个href与URL之间的关系,但是如何检查URL中匹配的锚链接名称或类似的内容呢?

  $('.main-nav li > a').each(function () {
    var $this = $(this);
    if ($this.attr('href').indexOf(location.pathname) !== -1) {
      $this.addClass('active');
    }
  });

共1个答案

匿名用户

如果您将“.html”从它们的末尾截断,并在该位置中搜索A的href(应该更短),它应该会起作用。

  $('.main-nav li > a').each(function () {
    var $this = $(this);
    var loc = location.
    if (location.pathname.replace(/\/[^\/]*\.html$/, '').startsWith($this.attr('href').replace(/\.html$/, ''))) {
      $this.parent().addClass('active');
    }
  });

您可以在这里的“action”中看到它:https://jsfidle.net/c8u2f91v/注意它使用了一个假的location_pathname而不是location.pathname,因为jsfiddle在路径中没有必要的前缀,但它表明它应该可以工作。