[英]jQuery Navigation add active class
我的代碼以某種方式無法添加活動類。 如果選擇了第一個菜單,則它將添加到<nav>
,自身<li>
和下一個<li>
活動類。
<nav id="cssmenu" class="sidebox_content active">
<ul class="navmenu">
<li class="active">
<a href="Neu-im-Sortiment">Neue Produkte</a>
</li>
<li class="has-sub top-cat active"></li>
</ul>
</nav>
這是我正在使用的Javascript
$(document).ready(function () {
var url = window.location;
// Will only work if string in href matches with location
$('ul.navmenu a[href="' + url + '"]').parent().addClass('active');
// Will also work for relative and absolute hrefs
$('ul.navmenu a').filter(function () {
return this.href == url;
}).parent().addClass('active').parent().parent().addClass('active');
});
如果單擊第二個列表,那么一切都將像超級按鈕一樣工作。 .partent()錯誤嗎?
我假設以下內容:
a
的li
和nav
祖先元素添加active
類。 Neu-im-Sortiment
的href
(例如“ http://example.com/products/Neu-im-Sortiment ”) 我懷疑主要問題是window.location
是一個對象,而不是字符串。 對於此帖子的網址,它看起來像這樣:
window.location = {
"ancestorOrigins": {
"length": 0
},
"origin": "http://stackoverflow.com",
"hash": "",
"search": "",
"pathname": "/questions/23985401/jquery-navigation-add-active-class",
"port": "",
"hostname": "stackoverflow.com",
"host": "stackoverflow.com",
"protocol": "http:",
"href": "http://stackoverflow.com/questions/23985401/jquery-navigation-add-active-class"
};
您可以使用window.location.href
,但是完整的URL可能對您的目的沒有幫助。 請嘗試使用window.location.pathname
。
$(document).ready(function () {
"use strict";
var path = window.location.pathname, // skip the domain and truncate any hashtag nonsense and/or url parameters
link = $('ul.navmenu a').filter(function (i) {
var startOfPath = path.indexOf(this.href) === 1, // pathname starts with a slash
anywhereInPath = path.indexOf(this.href) > -1,
endOfPath = path.indexOf(this.href) === path.length - this.href.length;
return startOfPath || anywhereInPath || endOfPath; // anywhereInPath is most likely to be true
}),
li = link.parents('li'), // to get the LI element, or you could do link.parent(), since the LI is the immediate ancestor
nav = link.parents('nav'); // to get the NAV element, or you could do li.parents('nav'), or you could do li.parent().parent() (etc.)
li.addClass('active'); // add class to LI
nav.addClass('active'); // add class to NAV
// or you could do both with the same call:
// $(li, nav).addClass('active');
});
壓縮語法(全部鏈接):
$(document).ready(function () {
"use strict";
var path = window.location.pathname;
$('ul.navmenu a').filter(function (i) { // this selects all A elements that have an ancestor UL with class "navmenu"
var existsInPath = yourLogic(); // and returns only those that match this criteria
return existsInPath;
}).parents('li').addClass('active').parents('nav').addClass('active');
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.