[英]Add Active Navigation Class Based on Child Page URL
我有一个基本的侧边菜单结构,它是根据帖子主题动态生成的。 使用以下代码,我可以在查看各个主题页面时按预期突出显示活动链接。 但是,在列出所有主题的主页或索引页面上,侧面导航中的每个锚点元素都被赋予一个“活动”类。 如何防止索引页面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>
使用主题索引页面上的上述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>
尝试此操作,以这种方式添加最新密钥到当前可能是协议问题,您可以始终确保
$(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');
}
});
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.