可以将文章内容翻译成中文,广告屏蔽插件可能会导致该功能失效(如失效,请关闭广告屏蔽插件后再试):
问题:
I have this JS code for my menu:
$(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?
I have created a jsfiddle here so you can see the full html and css etc: http://jsfiddle.net/bMkEj/
回答1:
It can be done using HTML5 LocalStorage.
In the click handler, save the active menu text to localStorage:
$('#nav > li > a').click(function(e){ ... localStorage.setItem("activeSubMenu", $(this).text()); });
On page load, read the localStorage and expand the menu (if found):
$(document).ready(function(){ var activeItem = localStorage.getItem("activeSubMenu"); if(activeItem){ $('#nav > li > a').filter(function() { return $(this).text() == activeItem; }).slideToggle(); } });
回答2:
Pass a query parameter when you load the page and use it to select the appropriate nav item:
HTML
<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>
JS (assumes jQuery)
$(document).ready(function() { var query = decodeURIComponent(window.location.search); var matches = query.match(/nav=([^&]*)/); var id = matches[1]; $('#' + id + ' ul').slideDown(); });
回答3:
If you're running PHP, or any other server-end language, you could add the active class to the active element.
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.