jquery Cookie设置并获得div的扩展状态

我有一个与此主题相关的问题和问题。 我有多个div通过c#代码动态加载。 我们无法计算需要在网页中显示的面板(每个类别)的数量。 它可能是单个或4或5有时更多。 前面的代码按预期正常工作。

现在,我想在回发或页面刷新时保留每个div的折叠或展开状态。 我尝试使用jquery cookie,但我们似乎无法设置并获取每个部分的cookie状态。

我试过的代码是

jQuery(function ($) { var $heads = $(".toggle-container .toggle-header"); $heads.click(function () { var $this = $(this); $this.find('i').toggleClass('icon-chevron-sign-down icon-chevron-sign-up'); $this.next().slideToggle("slow"); if ($this.next().is(':visible')) { $.cookie('expanded', 'true'); } else { $.cookie('expanded', 'false'); } }); var cookieValue = $.cookie("expanded"); if (cookieValue === "true") { $heads.next().show(); } else { $heads.next().hide(); } }); 

JsFiddle游乐场: http : //jsfiddle.net/ravimallya/qL79j/

更新:

我也试过这个: http : //jsfiddle.net/ravimallya/qL79j/7/ 。 我不能改变标记而不是这个。

任何人都可以尝试一下吗? 提前致谢。

将ID设置为所有块,并根据ID创建cookie。 像这样:

工作演示

 $('.block').click(function(){ if ( $(this).find('.outer').css('display') == 'block' ) { $(this).find('.outer').slideUp('normal'); $.cookie($(this).attr('id'), 'hide'); } else { $(this).find('.outer').slideDown('slow'); var tab_cookie = $.cookie($(this).attr('id')); if ( tab_cookie == 'hide' ) { $.cookie($(this).attr('id'), 'show'); } } }); 

然后使用此代码:

 $(document).ready(function(){ $('.block').each(function(){ var block =$(this).attr('id'); if ( $.cookie(block) == 'hide' ) { $(this).find('.outer').hide(); } }); }); 

更新

在您的情况下使用此代码:

工作演示

 jQuery(function ($) { $('.toggle-container').each(function () { var block = $(this).attr('id'); if ($.cookie(block) == 'hide') { $(this).find('.toggle-content').hide(); } else { $(this).find('.toggle-content').show(); /* show visible element */ } }); $('.toggle-header').click(function () { if ($(this).next().css('display') == 'block') { $(this).next().slideUp('normal'); $.cookie($(this).parent().attr('id'), 'hide'); } else { $(this).next().slideDown('slow'); var tab_cookie = $.cookie($(this).parent().attr('id')); /* missed parent() here */ if (tab_cookie == 'hide') { $.cookie($(this).parent().attr('id'), 'show'); } } }); });