我想保存站点标题显示的状态。我如何使用 Jquery Cookie 保存它?
(function ($) {
// The initial load event will try and pull the cookie to see if the toggle is "open"
var openToggle = getCookie("show") || false;
if ( openToggle )
div.style.display = "block";
else
div.style.display = "none";
if ( window.location.pathname == '/' ){
// Index (home) page
div.style.display = "block";
}
// The click handler will decide whether the toggle should "show"/"hide" and set the cookie.
$('#Togglesite-header').click(function() {
var closed = $("site-header").is(":hidden");
if ( closed )
div.style.display = "block";
else
div.style.display = "none";
setCookie("show", !closed, 365 );
});
});
最佳答案
您这里有几个问题。首先,您定义了一个类似 IIFE 的函数包装器,但您从未调用它,因此您的代码将不会运行。您需要将 (jQuery)
添加到末尾以传递引用,或者根据您的意图使用实际的 document.ready
事件处理程序。
其次,cookie仅存储字符串,因此您需要将字符串转换为 bool 值(这对于JS的数据类型来说有点雷区),或者您可以只比较字符串。试试这个:
(function($) {
var $div = $(div);
var openToggle = getCookie("show") == 'true';
$div.toggle(openToggle);
if (window.location.pathname == '/')
$div.show();
$('#Togglesite-header').click(function() {
var closed = $("site-header").is(":hidden");
$div.toggle(closed);
setCookie("show", !closed, 365);
});
})(jQuery);
还有两件事需要注意。首先我修改了它以使用 jQuery。如果您已经加载了它,您也可以利用它的简单性来减少代码的冗长。
其次,它假设您的 getCookie()
和 setCookie()
函数正在运行;您还没有展示它们的实现,但由于有很多工作示例,我不认为这是您的问题。
关于javascript - 使用 cookie 保存 Javascript 切换状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52201922/