gpt4 book ai didi

javascript - jQuery 导航添加事件类

转载 作者:行者123 更新时间:2023-12-02 17:20:45 25 4
gpt4 key购买 nike

不知何故,我的代码在添加事件类时遇到问题。如果选择第一个菜单,则会添加到 <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() 是否错误?

最佳答案

我假设如下:

我怀疑主要问题是 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');
});

关于javascript - jQuery 导航添加事件类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23985401/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com