[英]Active navigation class based on current URL problem
我有以下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>
然后我有這段代碼:
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');
}
})
})
該代碼運行良好,但是有問題。 例如,如果我看到主頁(www.example.com),則所有菜單鏈接都會收到活動的類。 另一個問題是它對www.example.com/something很好用,但是如果我訪問www.example.com/something/1等,它就不能保持活動狀態。您知道如何解決此問題嗎? 提前致謝!
使用下面的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");
})
});
對於主頁,在列表中添加額外的類“默認”。
<li class="first default"><a href="/">Home</a></li>
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');
}
})
通過使用indexOf(),您正在檢查鏈接的目標是否與當前位置相同。
您想要的不是“相同的URL”,而是“相同的模式”,所以我傾向於使用正則表達式:
let re = new RegExp("^" + $(this).attr("href") + ".*");
if (re.test($current)) {
$(this).addClass("active");
}
請注意,這將迫使您為指向主頁的鏈接創建單獨的解決方案,否則它將始終處於活動狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.