[英]How to keep a submenu open when the page changes
I have this JS code for my menu: 我的菜单有这个JS代码:
$(document).ready(function () {
$('#nav > li > a').click(function(e){
if ($(this).attr('class') != 'active'){
$('#nav li ul').slideUp();
$(this).next().slideToggle();
$('#nav li a').removeClass('active');
$(this).addClass('active');
}
});
});
what is the best way to make the sub menus stay open when the page is changed - maybe using cookies or sessions? 在页面更改时使子菜单保持打开的最佳方法是什么 - 可能使用cookie或会话?
I have created a jsfiddle here so you can see the full html and css etc: http://jsfiddle.net/bMkEj/ 我在这里创建了一个jsfiddle,所以你可以看到完整的html和css等: http : //jsfiddle.net/bMkEj/
It can be done using HTML5 LocalStorage . 可以使用HTML5 LocalStorage完成。
In the click handler, save the active menu text to localStorage: 在单击处理程序中,将活动菜单文本保存到localStorage:
$('#nav > li > a').click(function(e){
...
localStorage.setItem("activeSubMenu", $(this).text());
});
On page load, read the localStorage and expand the menu (if found): 在页面加载时,读取localStorage并展开菜单(如果找到):
$(document).ready(function(){
var activeItem = localStorage.getItem("activeSubMenu");
if(activeItem){
$('#nav > li > a').filter(function() {
return $(this).text() == activeItem;
}).slideToggle();
}
});
Pass a query parameter when you load the page and use it to select the appropriate nav item: 加载页面时传递查询参数并使用它来选择适当的导航项:
<ul>
<li id="foo"><a href="index.html?nav=foo">Foo</a>
<ul>
<li>Foo 1</li>
<li>Foo 2</li>
</ul>
</li>
<li id="bar"><a href="index.html?nav=bar">Bar</a>
<ul>
<li>Bar 1</li>
<li>Bar 2</li>
</ul>
</li>
<li id="baz"><a href="index.html?nav=baz">Baz</a>
<ul>
<li>Baz 1</li>
<li>Baz 2</li>
</ul>
</li>
</ul>
$(document).ready(function() {
var query = decodeURIComponent(window.location.search);
var matches = query.match(/nav=([^&]*)/);
var id = matches[1];
$('#' + id + ' ul').slideDown();
});
If you're running PHP, or any other server-end language, you could add the active class to the active element. 如果您正在运行PHP或任何其他服务器端语言,则可以将活动类添加到活动元素。
EDIT: If you're just running JS you might be able to parse the url (window.location.href) and use that to set the active class. 编辑:如果你刚刚运行JS,你可能能够解析url(window.location.href)并使用它来设置活动类。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.