【问题标题】:Set cookie for div state (java script)为 div 状态设置 cookie (javascript)
【发布时间】:2013-09-12 03:51:43
【问题描述】:

我有一个函数可以控制两个 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 样式保持选中状态,而不是默认设置?

感谢您的帮助!

【问题讨论】:

    标签: javascript jquery html css cookies


    【解决方案1】:

    我推荐你看看jQuery.Cookie,有了这个jQuery插件你可以轻松设置cookies。

    只需一行代码即可设置 Cookie:$.cookie('the_cookie', 'the_value');
    请注意,这只会为会话设置 cookie,您还可以像这样设置 cookie 到期日期:$.cookie('the_cookie', 'the_value', { expires: 30 });(“到期”以天为单位设置)。

    要读取 cookie 的值,您可以这样做:$.cookie('the_cookie');,如果 cookie 不存在,它将返回“undefined”。

    希望这对您有所帮助,如果这对您有用,请告诉我 ;)!

    【讨论】:

    • 感谢您的回复...但是,我不知道如何或在何处插入 $.cookie...您(或其他人)能给我一些指导吗?我真的不太了解js...TY
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-02-17
    • 2021-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-25
    • 2012-12-18
    相关资源
    最近更新 更多