How to remember last state with Jquery?

前端 未结 1 1356
有刺的猬
有刺的猬 2020-12-17 07:36

I have a menu with submenus that can be toggled (hide/show type deal). Is there a relatively easy way to remember last state of the menu? (I hide/show submenu when clicking

相关标签:
1条回答
  • 2020-12-17 08:01

    You can use the jQuery cookie plugin for this

    Just set the cookie when hiding, showing, then on load set what's shown based on any cookies set. You can do this by naming the cookies like this: "display" - this.id

    If you wrapped each menu with a <div id="unique"> like you have with geysers (so we have a unique ID to set a cookie for), something like this should work:

    $('h3').next('.g_menu').filter(function() {
      return $.cookie("expanded-" + $(this).parent("[id]").attr("id"));
    }).hide();
    
    $('h3').click(function(){
      $(this).toggleClass('closeit').toggleClass('openit');
      var menu = $(this).next('.g_menu');
        if(menu.is(':visible')) {
            menu.fadeOut(50);
            $.cookie("expanded-" + $(this).parent().attr("id"), true);
        } else {
            menu.fadeIn(980);            
            $.cookie("expanded-" + $(this).parent().attr("id"), null);
        }
    });​
    

    To make this work, wrap <h3 class="openit">Other</h3><div class="g_menu"></div> in a <div id="other"></div> You can play with a sample to see this in action here.

    0 讨论(0)
提交回复
热议问题