简体   繁体   English

使用jQuery Cookie保存div切换状态

[英]Save div toggle state with jquery cookie

I have an idea how to implement this, but it doesn't seem that of all the similar posts, anybody is able to give a simple example. 我有一个实现方法的想法,但似乎在所有类似的帖子中,没有人能举一个简单的例子。 I want to simply store the value of the toggle state of "marketing-message-global" in a cookie. 我只想在Cookie中存储“ marketing-message-global”的切换状态值。 If the user clicks "hide-marketing-message-btn", the toggled state will be stored in a cookie. 如果用户单击“ hide-marketing-message-btn”,则切换状态将存储在cookie中。 When the user refreshes the page, the stored toggle state will be used, and hide the div that was toggled off. 当用户刷新页面时,将使用存储的切换状态,并隐藏已关闭的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>

I used jquery cookie plugin ( https://github.com/carhartl/jquery-cookie ) 我使用了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:'/'}); 
});

});

I think this should work: 我认为这应该工作:

1) If you want to set the cookie by some events else: 1)如果您想通过其他事件设置cookie:

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

2) Setting cookie by clicking on div and performing toggle at once: 2)通过单击div并立即执行切换来设置cookie:

$(document).ready(function() {
    $("#hide-marketing-message-btn").click(function() { 
        if ($("#hide-marketing-message-btn").prop("hidden") == "hidden")
        {
            $("#marketing-message-global").hide();
            $.cookie("toggle-state") == true;
        }
        else
        {
            // ... 
        }
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM