我正在尝试使用 cookie 保存可折叠框的切换状态。这是我的代码:
HTML:
<div class="box_container">
<div class="box_handle">
Title
</div>
<div class="box" data-title="admin_actions">
Content
</div>
</div>
Javascript:
$('div.box_container div.box_handle').click(function() {
$(this).next('.box').slideToggle('fast');
});
$.each($('div.box_container div.box_handle'), function(index,value){
if ($.cookie('show_box_' + $(value).next('.box').attr('data-title')) != 'closed'){
$(value).next('.box[data-title="' + $('.box').attr('data-title') + '"]').hide();
}
});
var new_value = "";
window.onbeforeunload = function() {
$.each($('div.box_container div.box_handle'),function(index,value){
new_value = ($(value).next('.box').css('display') == 'none') ? 'open' : 'closed';
$.cookie('show_box_' + $(value).next('.box').attr('data-title'), new_value);
});
}
现在,我的问题是:
除第一个框之外的任何框都将始终显示为打开状态。它确实为其设置了一个cookie,但如果cookie设置为关闭
,则不会隐藏它仅对于页面上的每个第一个框起作用。我该如何解决这个问题?
最佳答案
使用javascript的onbeforeunload
函数
window.onbeforeunload = function() {
//Declare cookie to close state
}
每次页面刷新时都会调用此函数
更新:
要循环遍历每个值,请使用此$.each
:
var new_value = "";
window.onbeforeunload = function() {
$.each($('div.box_container div.box_handle'),function(index,value){
new_value = ($(value).next('.box').css('display') == 'none') ? 'collapsed' : 'expanded';
$.cookie('show_box' + '_' + $(value).next('.box').attr('data-title'), new_value);
})
}
更新二:
这样做,它应该有效
window.onload = checkCon;
function checkCon(){
$.each($('div.box_container div.box_handle'),function(index,value){
if ($.cookie('show_box' + '_' + $(value).next('.box').attr('data-title')) != 'expanded'){
$(value).next('.box[data-title="' + $(value).next('.box').attr('data-title') + '"]').hide();
}
})
}
关于javascript - SlideToggle 状态不适用于多个框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30974711/