【问题标题】:How to set and read cookies JavaScript如何设置和读取 cookie JavaScript
【发布时间】:2017-10-24 21:58:41
【问题描述】:

我正在尝试在您第一次访问我的网站时制作一个弹出窗口。但在那之后的任何其他时间都没有。所以我试着用饼干来做。但我绝对没有运气。

我已经尝试按照 W3 学校的教程进行操作,但我没有得到任何结果。 我正在做的是当用户关闭对话框时,它会设置一个 cookie。我正在努力做到这一点,所以当你回来时,不会出现弹出窗口,因为设置了 cookie。

这是我的代码。


function setCookie(cname,cvalue,exdays) {
  var d = new Date();
  d.setTime(d.getTime()+(exdays*24*60*60*1000));
  var expires = "expires="+d.toGMTString();
  document.cookie = cname + "=" + cvalue + "; " + expires;
}

function getCookie(cname) {
  var name = cname + "=";
  var ca = document.cookie.split(';');
  for(var i=0; i<ca.length; i++) {
    var c = ca[i].trim();
    if (c.indexOf(name)==0) 
      return c.substring(name.length,c.length);
  }  
  return "";
}

function checkCookie() {
  var username=getCookie("username");
  if (username!="") {
    $('#firsttimee').css({display : 'none'});
  } else {
    if (username=="" || username==null) {
      $('#firsttimee').css({display : 'block'});
    }
  }
}
        
function closepop(){
  $('#firsttimee').css({display : 'none'});
  var username = 'seen';
  setCookie("username",username,365);      
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="firsttimee">
  <div id="firsttimetxt">
    <center>
      <a href="http://blah.com/" id="bottomex">Click here</a>.<br><br>
      <a href="javascript:closepop()" id="bottomex">Done</a>
    </center>
  </div>
</div>

提前致谢! :) Here is a jsfidddle of my current work, for some reason when you click done the popup doesn't go away..

【问题讨论】:

    标签: javascript jquery cookies


    【解决方案1】:

    使用来自MDN 的 cookie 脚本,而不是 W3Schools,看起来 W3Schools 没有设置路径。

    var docCookies = {
      getItem: function (sKey) {
        return decodeURIComponent(document.cookie.replace(new RegExp("(?:(?:^|.*;)\\s*" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=\\s*([^;]*).*$)|^.*$"), "$1")) || null;
      },
      setItem: function (sKey, sValue, vEnd, sPath, sDomain, bSecure) {
        if (!sKey || /^(?:expires|max\-age|path|domain|secure)$/i.test(sKey)) { return false; }
        var sExpires = "";
        if (vEnd) {
          switch (vEnd.constructor) {
            case Number:
              sExpires = vEnd === Infinity ? "; expires=Fri, 31 Dec 9999 23:59:59 GMT" : "; max-age=" + vEnd;
              break;
            case String:
              sExpires = "; expires=" + vEnd;
              break;
            case Date:
              sExpires = "; expires=" + vEnd.toUTCString();
              break;
          }
        }
        document.cookie = encodeURIComponent(sKey) + "=" + encodeURIComponent(sValue) + sExpires + (sDomain ? "; domain=" + sDomain : "") + (sPath ? "; path=" + sPath : "") + (bSecure ? "; secure" : "");
        return true;
      },
      removeItem: function (sKey, sPath, sDomain) {
        if (!sKey || !this.hasItem(sKey)) { return false; }
        document.cookie = encodeURIComponent(sKey) + "=; expires=Thu, 01 Jan 1970 00:00:00 GMT" + ( sDomain ? "; domain=" + sDomain : "") + ( sPath ? "; path=" + sPath : "");
        return true;
      },
      hasItem: function (sKey) {
        return (new RegExp("(?:^|;\\s*)" + encodeURIComponent(sKey).replace(/[\-\.\+\*]/g, "\\$&") + "\\s*\\=")).test(document.cookie);
      },
      keys: /* optional method: you can safely remove it! */ function () {
        var aKeys = document.cookie.replace(/((?:^|\s*;)[^\=]+)(?=;|$)|^\s*|\s*(?:\=[^;]*)?(?:\1|$)/g, "").split(/\s*(?:\=[^;]*)?;\s*/);
        for (var nIdx = 0; nIdx < aKeys.length; nIdx++) { aKeys[nIdx] = decodeURIComponent(aKeys[nIdx]); }
        return aKeys;
      }
    };
    

    并设置 cookie

    docCookies.setItem("username",username,"Infinity");
    

    获取 cookie

    docCookies.getItem("username")  //returns the string
    

    或

    docCookies.has("username")  //return boolean
    

    【讨论】:

      【解决方案2】:

      我通常使用以下代码:

      function getCookie(cookieName) {
          var i, x, y, cookiesArray = document.cookie.split(";");
          for (i = 0; i < cookiesArray.length; i++) {
              x = cookiesArray[i].substr(0, cookiesArray[i].indexOf("="));
              y = cookiesArray[i].substr(cookiesArray[i].indexOf("=") + 1);
              x = x.replace(/^\s+|\s+$/g, "");
              if (x == cookieName) {
                  return unescape(y);
              }
          }
      }
      
      function checkCookie() {
          hideCookieDiv();
          var myCookie = getCookie("yourcookiename");
          if (myCookie == null || myCookie != "true") {
              showCookieDiv();
              setCookie();
          }
      }
      
      function hideCookieDiv() {
          document.getElementById('YourDivId').style.display = "none";
      }
      
      function showCookieDiv() {
          document.getElementById('YourDivId').style.display = "block";
      }
      
      function setCookie() {
          var expirationDate = new Date();
          expirationDate.setDate(expirationDate.getDate() + 365);
          document.cookie = "yourcookiename=true; expires=" + expirationDate.toUTCString();
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-08-01
        • 1970-01-01
        • 2018-12-21
        • 2016-11-06
        • 1970-01-01
        • 1970-01-01
        • 2015-12-08
        • 1970-01-01
        相关资源
        最近更新 更多