Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
521 views
in Technique[技术] by (71.8m points)

cookies - How to remember last state with Jquery?

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 on a header and change a style of the header so the background arrow will change (up/down)). It works fine, but I'd like it to remember last state, so when user goes to another page on the site and gets back, the menu shows the same way as user left it. I'm not really good with cookies so any help will be appreciated. Yeah, menu is generated dynamically from the db using PHP. There are now only 2 headers with submenus, but there will be more so I'd need some method that's "scalable" for any number of submenus. There is also no need to remember it for longer then one visit.

Current url is this: http://valleyofgeysers.com/geysers.php

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...