我知道如何实现这一点,但似乎在所有类似的帖子中,没有人能够给出一个简单的例子。我想简单地将“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/