简体   繁体   中英

Having trouble maintaining state on custom jQuery menu

Check out the treatments menu on right hand side of this website. It has a set of <dt> tags with an <a> tag and a <ul> list of submenu <li> links inside. The top level link and sumbmenu links are grouped together using the rel attribute.

As you can see the submenu slides down when you click the top level link. What I'm trying to do is maintain state between page loads so that if any of the links in the submenus are clicked it will stay open. I am trying to use the rel attribute to do this.

Here is my code so far, I am getting a bit confused with the logic:

function initMenu() {
    $('.menu ul:not(.active)').hide();

    var checkCookie = $.cookie("nav-item");
    if (checkCookie != "") {
        $('.menu').each(function () {
            var state = $(this).find('a:first-child').attr('rel');
            if (state == checkCookie) {
                alert(state);
                $(this).next().slideToggle('normal');       
            }
        })       
    }

    $('.menu > a:first-child').click(function(e) {
        e.preventDefault();
        var navIndex = $(this).attr('rel');
        $.cookie("nav-item", navIndex);

        $(this).next().slideToggle('normal');
    });
}  

$(function() {
    initMenu();
});

EDIT** I have changed the first part of the code to this in order to try and use the active class. But what its doing is opening all the ul's instead of just the ul that contains the li with the active class.

$('.menu ul:not(.active)').hide();

 $('.menu').each(function (){

   if ($(this).children(".active")){

       $(this).children('ul').slideToggle('normal');  
   }


 });       

Update * after update of original question *

Use for the if

if ($(this).find(".active").length){
       $(this).children('ul').slideToggle('normal');  
   }

Original answer

One thing is with

if (state == checkCookie) {
    alert(state);
    $(this).next().slideToggle('normal');       
}

this in this context refers to .menu and not the a link.

You should change it to

if (state == checkCookie) {
    alert(state);
    $(this).children('ul').slideToggle('normal');       
}

The other is that the cookie plugin creates (by default) cookies that belong to the page that created them. So when you change a page it does not have access to a cookie created by another page.

Use the path option when saving $.cookie("nav-item", navIndex, {path: '/'});


The correct way

It would be best though not to rely on cookies for navigation as it will become problematic when a user starts using the back button ..

You should really pass the rel value to the url as the hash #relvalue and use that instead.
( hint : check out window.location.hash )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM