Saving multiple panel's collapsed state using cookies with $.cookie()

前端 未结 5 1143
野性不改
野性不改 2021-02-01 19:12

I\'m trying to determine how I might save a collapsible panel\'s collapsed state using $.cookie.

This question has been helpful so far, but still missing the end soluti

5条回答
  •  别跟我提以往
    2021-02-01 19:32

    You should save the active panels in an array and store it in a cookie instead saving only 1 id at a time.

    Your JS should be like this:

    var activePanels = []; // array for the active panels
    $(".panel .panel-collapse").on('shown.bs.collapse', function ()
    {   
        var active = $(this).attr('id');
        activePanels.push(active); // store the active panel id into the array
        $.cookie('activePanelGroup', activePanels); // add array to the cookie
        console.log($.cookie('activePanelGroup')); // display current active panels stored in the cookie
    });
    
    $(".panel .panel-collapse").on('hidden.bs.collapse', function ()
    {
        var selectedPanel = $(this).attr('id');
        var index = activePanels.indexOf(selectedPanel);
        if (index > -1) // if id exists on the active panels array
          activePanels.splice(index, 1); // remove it on the active panels array
        $.cookie('activePanelGroup', activePanels); // add the updated active panels array to remove the old one
        console.log($.cookie('activePanelGroup')); // display current active panels stored in the cookie
    });
    
    var aPanels = $.cookie('activePanelGroup');  // retrieve all active panels 
    
    if (aPanels != null)
    {   
        //remove default collapse settings
        $(".panel .panel-collapse").removeClass('in');
        // put all active ids to array
        var arr = aPanels.split(",");
        // loop on each active panels
        $.each( arr, function( key, value ) {
          //show the account_last visible group
          $("#" + value).addClass("in");
    
          // store again the selected panels so it won't get reset on reload
          activePanels.push(value);
          $.cookie('activePanelGroup', activePanels);
        });
    }
    

    Fiddle

提交回复
热议问题