JS Cookie hide/show div

徘徊边缘 提交于 2019-11-30 19:58:13

问题


Trying to make a jQuery cookie hide/show box using JS Cookie, but I somehow can't make it work. The box won't display at all. I'm using Shopify.

#pop-up {
    display: none;
}

Jquery:

<script type='text/javascript'>//<![CDATA[
  $(window).load(function(){
  // if no cookie
  if (!$.cookie('alert')) {
      $( "#pop-up" ).show();
      $("#hide").click(function() {
          $( "#pop-up" ).slideUp( "slow" );
          // set the cookie for 24 hours
          var date = new Date();
          date.setTime(date.getTime() + 24 * 60 * 60 * 1000); 
          $.cookie('alert', true, { expires: date });
      });
  }
  });//]]> 
</script>

The rest:

<div id="pop-up">
  <div id="center" class="box">
    40% off today only<br>
    <a id="hide" href="#">OK, thanks!</a>
  </div>
</div>

回答1:


It does not work because you can only store strings in cookies. You store the string "true" instead of the boolean value true.

Try the following code where I replaced the check with != "true".

<script type='text/javascript'>//<![CDATA[
  $(window).load(function(){
  // if no cookie
  if ($.cookie('alert')!="true") {
      $( "#pop-up" ).show();
      $("#hide").click(function() {
          $( "#pop-up" ).slideUp( "slow" );
          // set the cookie for 24 hours
          var date = new Date();
          date.setTime(date.getTime() + 24 * 60 * 60 * 1000); 
          $.cookie('alert', "true", { expires: date });
      });
  }
  });//]]> 
</script>

A working jsfiddle: http://jsfiddle.net/bqam0qb4/1/



来源:https://stackoverflow.com/questions/34018078/js-cookie-hide-show-div

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!