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

前端 未结 5 1041
野性不改
野性不改 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:49

    
    
    
    
        
    Position shape

    Let me throw in an additional alternative: if you have customized the bootstrap panel example like me and ended up with multiple nesting for your accordion,then assuming you have unique ids for your collapsing & expanding element (the panel that expands or collapses), you can trap the (rely on) click event to get the id of the panel collapsing/expanding no matter how deep it's located in the nesting.

    I customized the examples in stackoverflow to achieve this; basically it gets the id of the expanded panel on click event, creates a cookie with the id as name (var temp) which will be used to remove it later if panel is collapsed. Then loop through cookie on page refresh (or etc.) to restore the accordion state. I must mention that cookies are not recommended for this type of spec. Thus, you can change the code to use localStorage or Javascript array. Hope this helps someone.

        $(document).on('shown.bs.collapse', function (e) {
               //whenever and wherever a panel is shown on any level of the  nesting, save the id in a cookie
                var active = $(e.target).attr('id')
               var temp = active;
                $.cookie(temp, active);
                console.log("panel expanded: ");
            });
    
            $(document).on('hidden.bs.collapse', function (e) {
                var temp = $(e.target).attr('id')
               //whenever and wherever a panel is collapsed on any level of the  nesting, remove the corresponding cookie
                $.removeCookie(temp);
                console.log("panel collapsed: ");
    
            });
    
            function restoreActiveAccordionGroup() {
                 var last = [];
                 last = $.cookie();
                if (last) {
    
                    //remove default collapse settings from all panels
                    $("#accordion").removeClass('in');
                    for (var i in last) {
                    //restore the last visible panel group in all nested levels
                    $("#" + i).addClass("in");
                    }
    
                }
            }
    

提交回复
热议问题