【问题标题】:Add active class to anchor based on url根据 url 添加活动类到锚点
【发布时间】:2018-02-19 00:46:56
【问题描述】:

我正在尝试添加活动类以基于 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');

【问题讨论】:

  • location.pathname.split("/")[1] 你确定 1 吗?
  • 试试location.href.split("/").pop()@Learning
  • @TemaniAfif,你说得有道理,让我看看 [1] 得到了什么
  • @Varun,我已经尝试过使用 .pop 的示例,它没有添加任何活动类
  • @Learning:如果你在控制台输入:location.pathname,你会得到什么?

标签: javascript jquery html css


【解决方案1】:

试试这个,

在 JS 中,

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

不要在 codepen 中尝试,那里的 URL 更改。 但是当我尝试时,此代码有效并将最后一个代码更改为黄色。 注意$ 而不是^

【讨论】:

    【解决方案2】:

    只需使用location.pathname

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

    【讨论】:

      猜你喜欢
      • 2023-01-22
      • 1970-01-01
      • 2016-12-31
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 2020-05-28
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多