繁体   English   中英

将活动类添加到基于URL的锚点

[英]Add active class to anchor based on url

我正在尝试添加和活动类以基于URL锚定,但将活动类添加到所有锚定元素

<div class="year-wrapper">
  <a href="/articles/2017" class="year">2017</a>
  <a href="/articles/2016" class="year">2016</a>
  <a href="/articles/2015" class="year">2015</a>
  <a href="/articles/2014" class="year">2014</a>
  <a href="/articles/2013" class="year">2013</a>
</div>

https://codepen.io/anon/pen/vdpPdz

假设我的网址是http://localhost:49660/articles/2014那么它应该向2014锚元素添加活动类,同时向所有项目添加活动类。 尝试了几个不同的例子以取得成功。

//http://localhost:49660/articles/2014
 $(function () {
    $('.year-wrapper a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');
    //$('.year-wrapper a[href^="articles/2014"').addClass('active');

});
.year-wrapper { width:50%; padding:20px; background:#f5f5f5; color:black; margin:10% auto;}
.year{margin:10px; padding:10px; background:green;}
.active{background:yellow;}

我也尝试过:

$('.year-wrapper > a[href^="/' + location.pathname.split("/")[1] + '"]').addClass('active');

尝试这个,

在JS中

$('.year-wrapper a[href$="'+(location.href.split("/").pop())+'"]').addClass("active");

不要在codepen中尝试它,URL会更改。 但是这段代码有效,当我尝试时将最后一个更改为黄色。 注意$而不是^

只需使用location.pathname

当URL为http://localhost:49660/articles/2014location.pathname将为/articles/2014 ,因此$('.year-wrapper a[href^="' + location.pathname + '"]')可以表示2014年链接。

暂无
暂无

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

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