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

whhtz7ly  于 2023-11-17  发布在  jQuery
关注(0)|答案(5)|浏览(124)

我正在尝试确定如何使用$. 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");
}

3b6akqbq

3b6akqbq1#

这将在每个面板显示时为它创建一个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可能是一个更好的选择。

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

vtwuwzda

vtwuwzda2#

您应该将活动面板保存保存在一个数组中并将其存储在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

mccptt67

mccptt673#

<!-- 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>

字符串
让我再给你一个选择:如果你像我一样定制了引导面板的例子,并最终为你的 accordion 设置了多个嵌套,那么假设你为你的折叠和展开元素(展开或折叠的面板)设置了唯一的id,你可以捕获(依赖于)click事件来获取折叠/展开面板的id,不管它位于嵌套的多深。
我定制了stackoverflow中的示例来实现这一点;基本上,它会在单击事件时获取扩展面板的ID,并以该ID作为名称创建cookie(var temp),如果面板被折叠,将用于稍后删除它。然后在页面刷新时循环通过cookie(或等)来恢复 accordion 状态。我必须提到的是,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");
                }

            }
        }

ljsrvy3e

ljsrvy3e4#

您可以将设置放在一个cookie中(即逗号分隔),并在打开-关闭时更新它。

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

字符串
查看编辑过的JsFiddle示例here

编辑

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

dw1jzc5e

dw1jzc5e5#

我宁愿使用本地存储而不是cookie。
您只需要在本地存储器上为每个与其id关联的面板创建一个变量,在此存储面板的状态。
当加载页面时,只需循环所有面板类对象,检查其在本地存储中的相关变量,并根据值应用适当的类。

相关问题