javascript - 如何设置和读取cookie JavaScript

标签 javascript jquery cookies

我正在尝试制作一个弹出窗口,当您第一次访问我的网站时,该弹出窗口会出现在我的网站上。但此后的任何其他时间都不会。所以我想用 cookies 来做。但我完全没有运气。

我尝试遵循 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..

最佳答案

使用 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

关于javascript - 如何设置和读取cookie JavaScript,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22811065/

相关文章:

python - 在 Python 中访问 Firefox 3 cookie

c# - 动态创建选择元素并从共享点列表中填充选项

Javascript - Codepen 尝试使用数组更改我的 html 内容的顺序我的函数正在运行但不太好我不明白为什么

jquery - Webstorm 未在 jquery 中显示 id 和类

javascript - 在移动设备上禁用 stellar.js

jquery - 如何使固定表头与 tbody 数据同步水平滚动?

PHP phpMyAdmin 尝试打开时出错

ruby-on-rails - 如何将 session cookie 的 HttpOnly 设置为 false?

javascript - Div 在另一个 div 下方并在悬停时显示过渡

javascript - Mocha 在完成所有测试之前结束测试运行