javascript - 为 div 状态设置 cookie (javascript)

标签 javascript jquery html css cookies

我有一个控制两个 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/

相关文章:

javascript - 等待,文件准备就绪

javascript - 登录控制错误

jquery - 如何使用 simpleModal 插件滚动

html - "Expand down"HTML/CSS 或替代

javascript - 如果在 Angular2 中使用 ngFor 该元素有可用空间,如何渲染元素

javascript - 为什么 JSON.parse 在与字符串数组一起使用时有时会返回错误?

javascript - FP 方式的数组嵌套映射

javascript - window.h 在 JavaScript 中意味着什么?

html - 分配 line-height 以跨越 html 中的元素 buggy ?

html - CSS3 : Give height and width to background image