简体   繁体   English

将活动班级添加到所选锚点

[英]adding class active to the selected anchor

I've this jQuery code to toggle my active class between my anchors but sadly it is not working and it is adding the class active to all the anchors. 我有这个jQuery代码来在我的锚之间切换我的活动类,但遗憾的是它不起作用,并且正在将活动类添加到所有锚中。

$(function() {
  $('.categories-list li a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
});

and my anchors looks like that: 我的锚点看起来像这样:

<a href="/blog/category/motoring+advice+&amp;+tips" class="active">motoring advice &amp; tips</a>
<a href="/blog/category/motoring+news+&amp;+updates" class="active">motoring news &amp; updates</a>

The active class repeated on al of them which is not what i am trying to achieve. 在他们中的每一个上都重复了活跃的课堂,这不是我想要达到的目标。 i tried to edit it to be like that : 我试图将其编辑为:

$(function() {
  $('.categories-list li a[href^="/blog/category/' + location.pathname.split("/")[1] + '"]').addClass('active');
});

but still it didn't work. 但仍然没有用。

.categories-list li

This is just my ul class and my li 这只是我的ul类和我的li

您的jquery选择器匹配所有锚点,使用ID,更精确的选择器或使用.eq(x),其中x是所需节点的索引。

thats how i solve this problem. 那就是我如何解决这个问题。

$(document).ready(function() {
        addActiveClass();

        function addActiveClass() {
          var current = window.location.pathname;
          $('.categories-list-blog li a').each(function() {
            var link = '' + $(this).attr('href');
            if (current == link) {
              $(this).addClass('active');
            }
          });
        }
      });

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

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