Javascript 基于当前URL问题的主动导航类
我有以下HTML菜单:Javascript 基于当前URL问题的主动导航类,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我有以下HTML菜单: <div class="nav"> <ul> <li class="first"><a href="/">Home</a></li> <li><a href="/something/">Something</a></li> <li
<div class="nav">
<ul>
<li class="first"><a href="/">Home</a></li>
<li><a href="/something/">Something</a></li>
<li><a href="/else/">Else</a></li>
<li class="last"><a href="/random/">Random</a></li>
</ul>
<ul style="float:right;">
<li class="first last"><a href="/news/">News</a></li>
</ul>
</div>
</div>
代码运行得很好,但有一个问题。例如,如果我看到主页(www.example.com),那么所有菜单链接都会收到活动类。另一个问题是,它对www.example.com/something非常有效,但如果我访问www.example.com/something/1等,它不会保持活动状态。有没有办法解决这个问题?提前谢谢 使用以下jQuery代码添加
活动类:
$(function() {
var pgurl = window.location.href.substr(window.location.href
.lastIndexOf("/") + 1);
$(".nav ul li a").each(function() {
if ($(this).attr("href") == pgurl || $(this).attr("href") == '')
$(this).addClass("active");
})
});
对于主页,在列表中添加额外的类“default”,如
<li class="first default"><a href="/">Home</a></li>
通过使用indexOf(),您可以检查链接的目标是否与当前位置相同
您想要的不是“相同的URL”,而是“相同的模式”,因此我倾向于使用正则表达式:
let re = new RegExp("^" + $(this).attr("href") + ".*");
if (re.test($current)) {
$(this).addClass("active");
}
请注意,这将迫使您为主页的链接创建一个单独的解决方案,否则它将始终处于活动状态。谢谢,但它不起作用。主页已激活,但无法识别其他主页。请从列表项中删除结束斜杠。比如-我可以给你TeamViewer。“主页”选项卡保持打开状态,而其他选项卡处于打开或关闭状态。编辑#1:我删除了结束斜杠,仍然没有任何内容。对于www.example.com/something,当前路径将是“/something”,但在列表项中您使用的是/something/。删除结束斜杠并检查。因为在最后一项中,您也使用了“first”类。谢谢您的回答,但它似乎不起作用。
jQuery(function($){
var current = location.pathname;
console.log(current);
//remove the active class from list item.
$('.nav ul li a').removeClass('active');
if(current != '/'){
$('.nav ul li a').each(function(){
var $this = $(this);
// if the current path is like this link, make it active
if(current.indexOf($this.attr('href')) !== -1 && $this.attr('href') != '/'){
$this.addClass('active');
}
})
}else{
console.log('home');
$('.default a').addClass('active');
}
})
let re = new RegExp("^" + $(this).attr("href") + ".*");
if (re.test($current)) {
$(this).addClass("active");
}