简体   繁体   English

如何设置和读取JavaScript JavaScript

[英]How to set and read cookies JavaScript

I'm trying to make a popup that appears on my site the first time you visit it. 我正在尝试在您第一次访问时在我的网站上显示一个弹出窗口。 But not any other time after that. 但那之后没有任何其他时间。 So I'm trying to make it with cookies. 所以我试图用饼干制作它。 But I'm having absolutely no luck. 但我绝对没有运气。

I've tried following W3 school's tutorial but I haven't gotten anywhere. 我试过按照W3学校的教程,但我没有得到任何结果。 What I'm doing is when the user closes the dialog, it sets a cookie. 我正在做的是当用户关闭对话框时,它会设置一个cookie。 And I'm trying to make it so when you come back, the pop up doesn't appear because the cookie is set. 而且我试图这样做,当你回来时,弹出窗口没有出现,因为cookie已经设置好了。

Here's my code. 这是我的代码。


 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> 

Thanks in advance! 提前致谢! :) Here is a jsfidddle of my current work, for some reason when you click done the popup doesn't go away.. :) 这是我当前工作的jsfidddle,由于某种原因,当你点击完成后,弹出窗口不会消失..

Use the cookie script from MDN , not W3Schools, looks like W3Schools is not setting the path. 使用来自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;
  }
};

and to set the cookie 并设置cookie

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

and to get the cookie 并获得cookie

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

or 要么

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

I usually use below code for that: 我通常使用下面的代码:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM