如果存在cookie,如何隐藏div [英] How to hide a div if cookie exists

查看:98
本文介绍了如果存在cookie,如何隐藏div的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

希望通过单击按钮来生成cookie,然后让其检查cookie是否存在,cookie是否存在,然后隐藏div.

Looking to generate a cookie on a click of a button, then for it to check if the cookie exists, if the cookie exists then hide div.

这是我处理代码的地方,但似乎无法使if语句按预期运行..

Here is where I am at with my code, but I cannot seem to get the if statement to function as intended..

    (function ($) {
      
      $(".cookieSetter").click(function () {
         $.cookie('cookieMade', 'jobDone');
      });
      
      if ($.cookie('cookieMade', 'jobDone') == "true") {
        $('.box').hide();
      }
        
    })(jQuery);

    button {
      height: 48px;
      width: 112px;
      background: #fff;
      border: 2px solid #2d2d2d;
      color: #2d2d2d;
      font-size: 14px;
      font-weight: 600;
      text-transform: uppercase;
      cursor: pointer;
    }
    
    .blue {
      background: blue;
    }
    
    .box {
      width: 100px;
      height: 100px;
      margin-top: 10px;
    }

    <a class="cookieSetter" href="#"><button>Set cookie</button></a>
    <div class="blue box"></div>

推荐答案

您使用的$.cookie('cookieMade', 'jobDone')是cookie的设置方法,而不是getter.如果要获取cookie的值,则应使用$.cookie('cookieMade'),并检查返回的值:

Your usage of $.cookie('cookieMade', 'jobDone') is the setter of the cookie and not the getter. If you want to get the value of the cookie you should use $.cookie('cookieMade'), and check the returned value:

if ($.cookie('cookieMade') == 'jobDone') {
    // Do something if the cookie's value is 'jobDone'
}

在您的情况下:

if ($.cookie('cookieMade') == 'jobDone') {
    // Do something if the cookie's value is 'jobDone'
    $('.box').hide();
}

更新

codepen的问题在于,每次重新加载页面时,都会得到一个不同的path,默认情况下,$.cookie将cookie的路径设置为当前路径.
您可以将path设置为/,以便该Cookie对您域中的所有页面均有效:

update

The problem with codepen is that each time you reload the page you get a different path, and by default, $.cookie sets the path of the cookie to the current path.
You can set the path to / so the cookie will be valid for all of the pages in your domain:

$.cookie('cookieMade', 'jobDone', {path: '/'});

这将在Codepen中工作(也应该在您的网站中工作).

This will work in codepen (and should also work in your website).

这篇关于如果存在cookie,如何隐藏div的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆