我想在当前网址上激活菜单项,现在是我的HTML:
<ul class="header-tools nav navbar-nav">
<li class="mysetting">
<a class="link-menu-active" href="">first title</a>
</li>
<li class="mysetting">
<a class="link-menu-active" href="">second title</a>
</li>
<li class="mysetting">
<a class="link-menu-active" href="">third title</a>
</li>
</ul>
它是我的jquery代码:
$(".header-tools.nav.navbar-nav li").each(function() {
var navItem = $(this);
if( $(navItem).find("a").attr("href") == location.href ) {
navItem.addClass("active");
}
});
或者它:
var path = window.location.pathname;
path = path.replace(/\/$/, "");
path = decodeURIComponent(path);
$(".header-tools.nav.navbar-nav li a").each(function () {
var href = $(this).attr('href');
if (path.substring(0, href.length) === href) {
$(this).closest('li').addClass('active');
}
});
但它们都不起作用,我该怎么办?
谢谢
答案 0 :(得分:0)
对于这个确切的用例,您可以检查当前路径是否匹配或包含锚点href并相应地采取行动。
$('.mysetting').each(function() {
var path = window.location.pathname,
href = $(this).find('a').attr('href'),
exactMatch = (path === href), // URL is the same as anchor. Useful when your path can contain the href of multiple links
closeMatch = (path.indexOf(href) !== -1); // URL contains anchor.
// Useful when you don't know if query strings and other crap will be appended/prepended to your links
if (exactMatch /* or closeMatch depending on your preference*/) {
$(this).addClass('active');
}
})
虽然正如上面的评论中已经指出的那样,WP内置的导航功能可以处理这种情况,并且比你能想到的任何几行javascript都强大得多。