【问题标题】:Save Javascript toggle state with cookie使用 cookie 保存 Javascript 切换状态
【发布时间】:2019-02-11 14:10:10
【问题描述】:

我想保存站点标题显示的状态。我如何使用 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 );
});

});

【问题讨论】:

  • 如何代码不起作用?那些set/getCookie 函数是什么?你能分享他们的实现吗?

标签: javascript jquery jquery-cookie


【解决方案1】:

这里有几个问题。首先,您定义了一个类似 IIFE 的函数包装器,但您从不调用它,因此您的代码将无法运行。您需要在末尾添加 (jQuery) 以传递引用,或者如果您愿意,请使用实际的 document.ready 事件处理程序。

其次,cookie 只存储字符串,因此您需要将字符串转换为布尔值(这有点像 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() 函数正在工作;您还没有展示他们的实现,但是由于有 很多 的工作示例,我认为这不是您的问题。

【讨论】:

  • 感谢您的解释,但由于我是 jquery 的初学者,所以我遇到了无法理解的错误。 'Uncaught ReferenceError: getCookie is not defined'
  • 这意味着您没有在页面中正确包含您正在使用的cookie库
  • 我用的是js-cookie:github.com/js-cookie/js-cookie 并用wp_enqueue_script加载,是不是错了?
  • 由于某种原因,该脚本未包含在内。不幸的是,我从未使用过 Wordpress,因此无法提供任何建议。如果您仍有问题,我建议您开始一个新问题或搜索。
猜你喜欢
  • 2014-05-22
  • 1970-01-01
  • 2013-08-16
  • 2015-08-30
  • 1970-01-01
  • 2021-06-13
  • 2011-03-30
  • 2014-08-13
  • 1970-01-01
相关资源
最近更新 更多