我有一个控制两个 div 的函数(collapse 和 collapse1)。如果一个设置为 style:block,另一个设置为 style:none。默认样式为 <div id="collapse1" style="display:none;">
和 <div id="collapse" style="display:block;">
这也总是在刷新或页面加载时检索到。
函数是这样的:
$(function () {
$('.nav-toggle').click(function () {
//get collapse content selector
var collapse_content_selector = $(this).attr('href');
//make the collapse content to be shown or hide
var toggle_switch = $(this);
$(collapse_content_selector).toggle(function () {
if ($(this).css('display') == 'none') {
toggle_switch.html('Show'); //change the button label to be 'Show'
document.getElementById('collapse').style.display = "block";
} else {
toggle_switch.html('Hide'); //change the button label to be 'Hide'
document.getElementById('collapse').style.display = "none";
}
});
});
});
那么,我如何为这个功能设置 cookie,以便在页面刷新时,div 样式保持选中状态,而不是默认样式?
感谢您的帮助!
最佳答案
我建议你看看jQuery.Cookie ,使用这个 jQuery 插件,您可以轻松设置 cookie。
只需一行代码即可设置 Cookie:$.cookie('the_cookie', 'the_value');
。
请注意,这只会为 session 设置 cookie,您还可以像这样设置 cookie 过期日期:$.cookie('the_cookie', 'the_value', { expires: 30 });
( “过期”以天为单位设置)。
要读取 cookie 的值,您可以这样做:$.cookie('the_cookie');
,如果 cookie 不存在,它将返回“undefined ".
希望这对您有所帮助,如果这对您有用,请告诉我 ;)!
关于javascript - 为 div 状态设置 cookie (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18684999/