使用$ .cookie()使用Cookie保存多个面板的折叠状态

时间:2015-11-03 15:06:00

标签: jquery twitter-bootstrap-3 jquery-cookie

我试图确定如何使用$ .cookie保存可折叠面板的崩溃状态。

到目前为止,

This问题一直有用,但仍然缺少最终解决方案。

到目前为止我找到的任何解决方案都只保存了最后一个下拉面板,因此当重新加载页面时,唯一保存的面板是最后一个。

我需要的是保存所有已滚动的面板而不是一个。

Link到Github上的jCookie插件。

Link在JSFiddle上演示

更新

有人建议LocalStorage是我想要实现的更合适的解决方案。如果您可以评论为什么以及本地存储是什么,将非常感激。

更新2

因为建议本地存储比使用Cookie解决此问题有所改进。选定的答案基于此。然而,正如Robin所提到的,在HTTPS站点上使用此技术存在缺点。

HTML

<div class="panel panel-default">
    <div data-toggle="collapse" data-target="#panel1" class="panel-heading collapsed">
        <h4 class="panel-title">
            <a> Panel 1 </a>
        </h4>
    </div>
    <div id="panel1" class="panel-collapse collapse">
        <div class="panel-body">
        </div>
    </div>
</div>


<div class="panel panel-default">
    <div data-toggle="collapse" data-target="#panel2" class="panel-heading collapsed">
        <h4 class="panel-title">
            <a> Panel 2 </a>
        </h4>
    </div>
    <div id="panel2" class="panel-collapse collapse">
        <div class="panel-body">
        </div>
    </div>
</div>


<div class="panel panel-default">
    <div data-toggle="collapse" data-target="#panel3" class="panel-heading collapsed">
        <h4 class="panel-title">
            <a> Panel 3 </a>
        </h4>
    </div>
    <div id="panel3" class="panel-collapse collapse">
        <div class="panel-body">
        </div>
    </div>
</div>

JQUERY

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

$(".panel .panel-collapse").on('hidden.bs.collapse', function ()
{
    $.removeCookie('activePanelGroup');
});

var last = $.cookie('activePanelGroup');
if (last != null)
{
    //remove default collapse settings
    $(".panel .panel-collapse").removeClass('in');
    //show the account_last visible group
    $("#" + last).addClass("in");
}

5 个答案:

答案 0 :(得分:20)

这将在每个面板显示时为其创建一个cookie,并在隐藏面板时删除cookie。

$(".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);
});

因此,在加载文档时,我们会检查每个cookie并展开面板。

$(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");
        }
    }    
});

使用LOCALSTORAGE

但是,正如有人建议的那样,使用localStorage可能是更好的选择。 localStorage非常适合这一点。

$(".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
});

加载页面时,获取localStorage的值并显示面板。

$(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");
        }
    }  
});

编辑:看到它正常工作:FIDDLE

答案 1 :(得分:3)

您应该将活动面板保存在一个数组中并将其存储在cookie中,而不是一次仅保存1 id

你的JS应该是这样的:

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

答案 2 :(得分:1)

您可以将设置放在一个Cookie中(即以逗号分隔)并在打开关闭时进行更新。

openPanels = $.cookie('activePanelGroup').split(",");

查看编辑好的JsFiddle示例here

修改

我同意克里斯的观点。我发现将所有值存储在一个cookie中是一个更优雅的解决方案,但是,我们应该记住单个cookie size limitations。 (这取决于浏览器)。

答案 3 :(得分:1)

&#13;
&#13;
<!-- when you have multiple levels of child-sections like this below - to hide/collapse or show and restore again -->
<!--here's how I kept track of their id's - ps. I have since removed the multiple -->
<!--tables but, it looked like this when I put this answer in -->

    <div class="panel-group" id="accordion">
        <div class="panel panel-default">
            <div class="panel-heading">
            </div>
            <div class="panel-body">
<!--TABLE 1-->
                <table class="table table-condensed" style="border-collapse: collapse;">
                    <tbody class="component-grp">
                        <tr data-toggle="collapse" data-parent="#accordion" data-target="#compogrp@x" class="accordion-toggle">
                            <td colspan="10">
                                <div class="">
                                </div>
                            </td>
                        </tr>
                        <tr>
                            <td class="hiddenRow">
                                <div class="accordian-body panel-collapse collapse" id="compogrp@x">
<!--TABLE 2-->
                                    <table class="table table-striped">
                                        <thead>
                                            <tr class="header">
                                                <th></th>
                                                <th>Position</th>
                                                <th>shape</th>

                                            </tr>
                                        </thead>
                                        <tbody class="component-row">
                                            <tr data-toggle="collapse" data-target="#comp-@x" class="accordion-toggle collapsed">
                                                <td>
                                                </td>
                                            </tr>
                                            <tr>
                                                <td colspan="10" class="hiddenRow">                                                
                                                </td>
                                            </tr>
                                        </tbody>
                                    </table>
                                </div>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>

        </div>

    </div>
&#13;
&#13;
&#13;

让我再提一个选择:如果您已经定制了像我这样的自举面板示例并最终为您的手风琴设置了多个嵌套,那么假设您有折叠的独特ID并且扩展元素(扩展或折叠的面板),您可以捕获(依赖)click事件以获取面板折叠/展开的ID,无论它在嵌套中的位置有多深。

我在stackoverflow中定制了这些示例以实现此目的;基本上它在click事件中获取扩展面板的id,创建一个id为name(var temp)的cookie,如果面板折叠,将用于删除它。然后在页面刷新(或等)上循环cookie以恢复手风琴状态。我必须提一下,不推荐使用这种规格的cookie。因此,您可以更改代码以使用localStorage或Javascript数组。希望这有助于某人。

    $(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");
                }

            }
        }

答案 4 :(得分:0)

我宁愿使用localStorage而不是cookies。

您只需要在本地存储上为与其相关联的每个面板创建一个变量,您可以在其中存储面板的状态。

加载页面时,只需循环所有面板分类对象,在本地存储中检查它的关联变量,并根据值应用适当的类。