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

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

    This will create a cookie for every panel when it's shown and remove the cookie when the panel is hidden.

    $(".panel .panel-collapse").on('shown.bs.collapse', function ()
    {
        var active = $(this).attr('id');
        $.cookie(active, "1");
    });
    
    $(".panel .panel-collapse").on('hidden.bs.collapse', function ()
    {
        var active = $(this).attr('id');
        $.removeCookie(active);
    });
    

    So, when loading the document, we check every cookie and expand the panel.

    $(document.ready(function(){
        var panels=$.cookie(); //get all cookies
        for (var panel in panels){ //<-- panel is the name of the cookie
            if ($("#"+panel).hasClass('panel-collapse')) // check if this is a panel
            {
                $("#"+panel).collapse("show");
            }
        }    
    });
    

    USING LOCALSTORAGE

    However, as someone suggested, using localStorage may be a better option. localStorage is great for this.

    $(".panel .panel-collapse").on('shown.bs.collapse', function ()
    {
        var active = $(this).attr('id');
        var panels= localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels);
        if ($.inArray(active,panels)==-1) //check that the element is not in the array
            panels.push(active);
        localStorage.panels=JSON.stringify(panels);
    });
    
    $(".panel .panel-collapse").on('hidden.bs.collapse', function ()
    {
        var active = $(this).attr('id');
        var panels= localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels);
        var elementIndex=$.inArray(active,panels);
        if (elementIndex!==-1) //check the array
        {
            panels.splice(elementIndex,1); //remove item from array        
        }
        localStorage.panels=JSON.stringify(panels); //save array on localStorage
    });
    

    When you load the page, get the values of localStorage and show the panels.

    $(document.ready(function(){
        var panels=localStorage.panels === undefined ? new Array() : JSON.parse(localStorage.panels); //get all panels
        for (var i in panels){ //<-- panel is the name of the cookie
            if ($("#"+panels[i]).hasClass('panel-collapse')) // check if this is a panel
            {
                $("#"+panels[i]).collapse("show");
            }
        }  
    });
    

    EDIT: See it working: FIDDLE

提交回复
热议问题