[英]Active navigation class based on current URL problem
I have the following HTML menu: 我有以下HTML菜单:
<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>
And then I have this code: 然后我有这段代码:
jQuery(function($){
var current = location.pathname;
$('.nav ul 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');
}
})
})
The code is working great, but it has a problem. 该代码运行良好,但是有问题。 For example, if I see the Home page (www.example.com) then all of the menu links receives the active class. 例如,如果我看到主页(www.example.com),则所有菜单链接都会收到活动的类。 Another problem would be that it works great for www.example.com/something but it doesn't keep it active if I go to www.example.com/something/1 etc. Any idea how to fix this? 另一个问题是它对www.example.com/something很好用,但是如果我访问www.example.com/something/1等,它就不能保持活动状态。您知道如何解决此问题吗? Thanks in advance! 提前致谢!
Use the below jQuery code to add active
class: 使用下面的jQuery代码添加active
类:
$(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");
})
});
For home page add extra class 'default' in list like. 对于主页,在列表中添加额外的类“默认”。
<li class="first default"><a href="/">Home</a></li>
jquery code. jQuery代码。
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');
}
})
By using indexOf(), you are checking if the link's target is the same the current location. 通过使用indexOf(),您正在检查链接的目标是否与当前位置相同。
What you want is not "the same URL" but "the same pattern", so I would tend to use a regular expression : 您想要的不是“相同的URL”,而是“相同的模式”,所以我倾向于使用正则表达式:
let re = new RegExp("^" + $(this).attr("href") + ".*");
if (re.test($current)) {
$(this).addClass("active");
}
Note that this would force you to create a separate solution for your link to the main page, else it would always be active. 请注意,这将迫使您为指向主页的链接创建单独的解决方案,否则它将始终处于活动状态。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.