用于30天的mouseleave弹出窗口的Cookie函数无法正常工作

时间:2014-08-08 19:53:56

标签: javascript cookies

目前有mouseleave popup工作,但希望将cookie与它集成30天。

这里是公共开发站点示例:http://www.doityourselfrv.com/services/

这是我拼凑的代码,但cookie无效:

var cookie_length = 30;

function setCookie(c_name,value,exdays) {
   var exdate=new Date();
   exdate.setDate(exdate.getDate() + exdays);
   var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
   document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
   var i,x,y,ARRcookies=document.cookie.split(";");
   for (i=0;i<ARRcookies.length;i++) {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^s+|s+$/g,"");
      if (x==c_name) {
         return unescape(y);
      }
   }
}

var show = getCookie("diyrvcooke");
if(show==null || show=="" || 1) {
    setCookie('diyrvcooke','1',cookie_length);
    //show popup here
}

2 个答案:

答案 0 :(得分:0)

尝试更改

if(show==null || show=="" || 1) {

if(show == null || show == "") {

在你的代码中,你检查1然后将cookie设置为1,这样它就不会被设置,或者如果它以某种方式设置,将保持设置......

答案 1 :(得分:0)

Plunker Example

<强> JS

var cookie_length = 30;

function setCookie(c_name,value,exdays) {
   var exdate=new Date();
   exdate.setDate(exdate.getDate() + exdays);
   var c_value=escape(value) + ((exdays===null) ? "" : "; expires="+exdate.toUTCString());
   document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name) {
   var i,x,y,ARRcookies=document.cookie.split(";");
   for (i=0;i<ARRcookies.length;i++) {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^s+|s+$/g,"");
      if (x==c_name) {
         return unescape(y);
      }
   }
}

var show = getCookie("diyrvcooke");
//show will be undefined the first time before a cookie is set.
if(show===undefined) {
    setCookie('diyrvcooke','1',cookie_length);
    //show popup here
    alert('popup here');
}