问题描述
基本上,我正在尝试将类active
添加到当前菜单项.通过使用以下jQuery代码,我成功了.
Basically, I'm trying to add the class active
to the current menu item. I succeeded by using the following jQuery code.
jQuery(document).ready(function($){
var path = window.location.href;
$('#nav-main li a').each(function() {
if (this.href === path) {
$(this).addClass('active');
}
});
});
我的导航栏如下:
<ul id="nav-main">
<li>
<a href="/">Home</a>
</li>
<li>
<a href="/brands">Brands</a>
</li>
<li>
<a href="/users">Users</a>
</li>
<li>
<a href="/employees">Employees</a>
</li>
</ul>
具有以下CSS:
ul#nav-main {
width: 1050px;
margin: 0 auto;
color: #fff;
}
ul#nav-main li {
margin: 0 5px 0 5px;
list-style-type: none;
text-align: center;
display: inline-block;
font-size: 17px;
}
ul#nav-main li a {
padding: 0 15px;
line-height: 2.692307692;
display: inline-block;
text-decoration: none;
color: #fff;
}
ul#nav-main li a:hover {
background-color: rgba(0, 0, 0, 0.3);
}
ul#nav-main li a.active {
background-color: rgba(0, 0, 0, 0.3);
}
现在,当我单击用户"时,转到/users
,jQuery代码成功添加了active
类,以便用户"在导航栏中显示为当前菜单项.但是,当我单击用户"页面上的链接时,该链接指向例如/users/view/12345
(其中12345
是用户的ID),因此用户"页面未显示为当前菜单项了.
Now, when I click on 'Users' I go to /users
and the jQuery code successfully adds the active
class so that 'Users' is shown as the current menu item in the navigation bar. However, when I click on a link on the 'Users' page which leads to, for example, /users/view/12345
(in which 12345
is the ID of a user), the 'Users' page isn't shown as the current menu item anymore.
我认为这与以下事实有关:jQuery代码仅在页面上查找nav-main li a
,而不查找其他a
.有什么我可以添加到我的jQuery代码中来完成这项工作的吗?
I think this has to do with the fact that the jQuery code only looks to nav-main li a
and not to other a
's at the page. Is there something I could add to my jQuery code to make this work?
推荐答案
尝试更改
var path = window.location.href;
对此:
var path = "/" + window.location.pathname.split('/')[1];
pathname
检索第一个斜杠之后(包括第一个斜杠)的所有内容. split
将根据定义的分隔符('/'
)将字符串分成字符串列表,我们将选择索引为1的项目.
pathname
retrieves everything after (and including) the first slash. split
will break the string into a list of strings based on a defined separator ('/'
), and we are going to choose the item with an index of 1.
这篇关于单击当前页面上的链接后,保持菜单项处于活动状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!