2017-09-04 35 views
0

我有这jQuery代码来切换我的活动类之间的锚点,但遗憾的是它不工作,它将活动类添加到所有锚点。将活动类添加到选定的锚点

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

和我的锚看起来像这样:

<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> 

活动类重复他们的人,这不是我想要的目的。我试图编辑它是这样的:

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

但仍然没有工作。

.categories-list li 

这只是我的ul类和我li

+0

你在'location.pathname'中得到了什么? – Shiladitya

+0

当前网址 –

+0

你可以在'location.pathname'中分享那个,再加上一点点'HTML'? – Shiladitya

回答

0

你的jQuery选择所有的锚,用一个ID,一个更精确的选择,或者使用.EQ(x),其中x是指数匹配你想要的节点。

0

多数民众赞成如何我解决这个问题。

$(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'); 
      } 
      }); 
     } 
     }); 
相关问题