问题描述
我有一个菜单: p>
HTML
< ul id = menuclass =sidebar>
< li> < a href =#class =clickme>菜单< / a>
< ul id =menu1>
< li>< a class =dropdown-class-namehref =#>下拉链接1< / a>< / li&
< li>< a class =dropdown-class-namehref =#>下拉link2< / a>< / li>
< / ul>
< / li>
b>
$('#menu1 li a' a')。removeClass('dropdown-class-name active');
$(this).addClass('dropdown-class-name active');
}
CSS
#menu1 li a.active {
font-weight:bold;
}
活动菜单项以粗体突出显示。但是在我的网站上,当我点击一些下拉链接,新页面打开,但活动菜单项已经不是粗体。
我试过这样做:
$(document).ready(function(){
var url = window.location.href;
$(#menu1 li a)。 (function(){
if(url ==(this.href)){
$('a')。removeClass('dropdown-class-name active');
$ this).addClass('dropdown-class-name active');
}
});
});
我认为这是正确的想法,但是在哪里可能会出错?
问题是,当您单击一个链接,它会导致重新加载菜单,并失去活动链接的状态。您在旧页面上设置活动的菜单项,然后浏览器跟随页面到新页面,在那里它不再处于活动状态,因为HTML再次加载,并且没有在菜单项上设置任何活动的类。 / p>
您必须做的是在页面加载时使用Javascript函数,检查哪个菜单项对应于当前URL并将该项设置为活动。因此,它将在链接被跟随之后设置活动类。新页面已加载,您将在新页面上看到它。
$(document).ready {
var url = window.location
var menuItem = $('#menu1 li a')。filter(function(){
return this.href == url;
})
menuItem.addClass('active');
})
I have a menu: http://jsfiddle.net/hu5x3hL1/1/
HTML
<ul id="menu" class="sidebar">
<li> <a href="#" class="clickme">Menu</a>
<ul id="menu1">
<li><a class="dropdown-class-name" href="#">Dropdown link1</a></li>
<li><a class="dropdown-class-name" href="#">Dropdown link2</a></li>
</ul>
</li>
jQuery
$('#menu1 li a').click(function(e) {
$('a').removeClass('dropdown-class-name active');
$(this).addClass('dropdown-class-name active');
});
CSS
#menu1 li a.active{
font-weight:bold;
}
Active menu item is highlighted in bold. But on my web-site when I click some drop down link, the new page opens, but active menu item already isn't bold. How to keep it highlighted in bold on the new page of the web-site?
I tried do this:
$(document).ready(function() {
var url = window.location.href;
$("#menu1 li a").click(function () {
if (url == (this.href)) {
$('a').removeClass('dropdown-class-name active');
$(this).addClass('dropdown-class-name active');
}
});
});
I think it's the right idea, but where can be mistake?
Problem is that when you click a link it causes a reload of the menu and loses the state of the active link. You're setting the menu item active on the old page, then browser follows page to the new page, where it's not active anymore, as the HTML is loaded again and it doesn't have any active classes set on the menu items.
What you have to do instead is to have a Javascript function on page load that checks which menu item corresponds to the current URL and sets that item active. Thus it'll set the active class after the link is followed & new page is loaded and you'll actually see it on the new page.
$(document).ready(function () {
var url = window.location
var menuItem = $('#menu1 li a').filter(function() {
return this.href == url;
})
menuItem.addClass('active');
})
这篇关于保持菜单项突出显示的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!