我有一个基本的侧面菜单结构,它是根据帖子主题动态生成的。使用code below我可以在查看单个主题页面时单独突出显示活动链接。但是,在列出所有主题的主页面或索引页面上,侧面导航中的每个锚元素都会被赋予“活动”类。如何在单个主题页面上保留“活动”类的同时防止索引页面sidenav锚点接收“活动”类?
提前感谢能够提供一些见解的任何人......
侧面导航结构:
<div class="sidenav">
<ul>
<li><a href="//example.com/customer/topic/government">Government</a></li>
<li><a href="//example.com/customer/topic/hospitality">Hospitality</a></li>
<li><a href="//example.com/customer/topic/industrial">Industrial</a></li>
</ul>
</div>
Javascript:
$(function(){
var current = location.pathname;
$('.sidenav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
})
})
在个别主题页面上使用上述JS的当前输出:
<div class="sidenav">
<ul>
<li><a href="//example.com/customer/topic/government">Government</a></li>
<li><a href="//example.com/customer/topic/hospitality" class="active">Hospitality</a></li>
<li><a href="//example.com/customer/topic/industrial">Industrial</a></li>
</ul>
</div>
在主题索引页面(/ customer)
上使用上述JS的当前输出<div class="sidenav">
<ul>
<li><a href="//example.com/customer/topic/government" class="active">Government</a></li>
<li><a href="//example.com/customer/topic/hospitality" class="active">Hospitality</a></li>
<li><a href="//example.com/customer/topic/industrial" class="active">Industrial</a></li>
</ul>
</div>
答案 0 :(得分:2)
尝试添加最后一个当前关键字可能是协议问题,这样你可以随时确定
$(function(){
var current = location.pathname;
current = current.substring(current.lastIndexOf('/'));
$('.sidenav li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if($this.attr('href').indexOf(current) !== -1){
$this.addClass('active');
}
});
});