【发布时间】: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