如何设置和读取JavaScript JavaScript

时间:2014-04-02 12:11:30

标签: javascript jquery 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);      
}
&#13;
<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>
&#13;
&#13;
&#13;

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

2 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

我通常使用以下代码:

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();
}