How to keep a submenu open when the page changes

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

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.



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!