问题描述:

CONTEXT

I'm using the following code to open/close an accordion menu:

 jQuery(function($) {

$('li').on('click', 'h4', function(){

//Expand or collapse this panel

$(this).next().slideToggle('slow');

});

});

This works fine, and keeps working even after DOM is re-generated by the Ajax load.

PROBLEM

However, if a certain section of the accordion is open, this does not persist through the Ajax load. I have seen people use cookies to remember the open/close state of each accordion category - is there any better way of doing this?

网友答案:

For any kind of temporary saving based on client side you can use session storage and for a long term saving you can use local storage.

This two are treated as a cookie, any for a complex data you can save in them a JSON-like-string.

网友答案:

ANSWER

For anyone else encountering this, here is what my code looked like in the end:

 jQuery(function($) {

   $(document).ajaxSuccess(function(){
     $('li h4 + ul').each(function(index){
       //get category name
       var text = $(this).prev().text();
       //get session storage indicating most recent category state
       var state = sessionStorage.getItem("'" + $(this).prev().text() + "'");

       //if state was closed, close it, etc.
       if(state == "closed"){
         $(this).hide();
       } else if(state == "open"){
         $(this).show();
       }
     });
   });

   $('form li').on('click', 'h4', function(){
     if($(this).next().is(":hidden")){
       $(this).next().slideToggle('slow');

       // Store the state of the current tab in session storage
       sessionStorage.setItem("'" + $(this).text() + "'", 'open');

     } else{
       $(this).next().slideToggle('slow');

       // Store the state of the current tab in session storage
       sessionStorage.setItem("'" + $(this).text() + "'", 'closed');
     }

   });

 });

I'm getting the text value of the current accordion tab, storing it as a key with a corresponding state in session storage, and then pulling that state on ajax load.

相关阅读:
Top