jquery - 使用 jquery cookie 保存 div 切换状态

标签 jquery jquery-cookie

我知道如何实现这一点,但似乎在所有类似的帖子中,没有人能够给出一个简单的例子。我想简单地将“marketing-message-global”的切换状态值存储在 cookie 中。如果用户点击“hide-marketing-message-btn”,切换状态将存储在 cookie 中。当用户刷新页面时,将使用存储的切换状态,并隐藏已关闭的 div。

<div id="marketing-message-global">
</div>
<div id="hide-marketing-message-btn">
</div>

$(document).ready(function() {
 if $('#hide-marketing-message-btn").clicked()
 {
    $("#marketing-message-global").hide();
    $.cookie("toggle-state") == true;
 }

if ($.cookie("toggle-state") == true)
{
    $("#marketing-message-global").hide();
}
else if ($.cookie("toggle-state") == false)
{
$("#marketing-message-global").show();
}
 });
</script>

最佳答案

我使用了 jquery cookie 插件 ( https://github.com/carhartl/jquery-cookie )

    $(function(){
       if($.cookie){
           //By default, if no cookie, just display.
           $("#marketing-message-global").toggle(!(!!$.cookie("toggle-state")) || $.cookie("toggle-state") === 'true');
    }

    $('#hide-marketing-message-btn').on('click', function(){
        $("#marketing-message-global").toggle();
        //Save the value to the cookie for 1 day; and cookie domain is whole site, if ignore "path", it will save this cookie for current page only;
        $.cookie("toggle-state", $("#marketing-message-global").is(':visible'), {expires: 1, path:'/'}); 
});

});

关于jquery - 使用 jquery cookie 保存 div 切换状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18238890/

相关文章:

javascript - jQuery 当前选中的单选按钮值始终显示第一个按钮值

javascript - 根据ajax响应结果隐藏div

jquery - 即使响应包含 ajax 请求的 'Set-Cookie' header ,cookie 也不存储在浏览器上

jquery - jQuery cookie 是否有可能像 session 变量一样过期?

javascript - Jquery Cookie 函数

javascript - 为 iframe 弹出窗口设置 cookie 以使其保持关闭

jquery - 使用 browserify-shim 伪造全局 jQuery? (找不到模块 'jquery')

javascript - 检查 CSS 类(通过单击按钮添加)是否存在并执行某些操作

javascript - 添加一个按钮到 javascript 测验的末尾,使用与 HTML 文件中使用的相同样式的按钮

javascript - 我无法使用 jQuery 脚本将我的 div 居中