问题
I have a question and issue related to this thread. I have multiple divs which are loaded dynamically through c# code. We can't count the number of panels (each category) that needed to be displayed in a webpage. It might be a single or 4 or 5 sometimes more. The previous code is working properly as expected.
Now, I want to retain the collapsed or expanded state of each div on a postback or page refresh. I tried to use jquery cookie, but we can't seem to set and get the cookie status for each sections.
The code that I have tried is
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 Playground: http://jsfiddle.net/ravimallya/qL79j/
Update:
I tried with this also: http://jsfiddle.net/ravimallya/qL79j/7/ . I can't change markup than this one.
Can anyone give a try? Thanks in advance.
回答1:
set ID to all of your blocks and create cookie based on IDs. like this:
Working DEMO
$('.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');
}
}
});
then use this code:
$(document).ready(function(){
$('.block').each(function(){
var block =$(this).attr('id');
if ( $.cookie(block) == 'hide' )
{
$(this).find('.outer').hide();
}
});
});
update
in your case use this code:
Working DEMO
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');
}
}
});
});
来源:https://stackoverflow.com/questions/21521358/jquery-cookie-set-and-get-expanded-status-of-divs