在页面上设置cookie以每天显示一次bootstrap弹出窗口

时间:2017-02-09 04:46:02

标签: javascript cookies

我正在学习JavaScript,我发现这个问题已被多次询问,但我无法让这个为我工作。 我想做的是,每天展示一次自举模式。

到目前为止我所拥有的是:

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

function getCookie(cookiename) {
  var name = cookiename + "=";
  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);
}


//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal, 
//if there is a cookie then return;
//The cookie should expire in one day. 
function checkCookie() {
   var showed = getCookie("showed");
   if (showed != null && showed != "") {
      var date = new Date(showed).getDate();
      var currentDate = new Date().getDate();

      if (currentDate > date) {
          return true;
      }
       return false;
   }
    return true;
}

现在,如果我改变最后一次返回true;返回虚假;我的模态没有显示出来。 现在的方式我每次都看到模态。 我究竟做错了什么? 我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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

    function getCookie(cookiename) {
  var name = cookiename + "=";
  var startPos = document.cookie.indexOf(name);
  if(startPos == -1) return null;
  startPos+=(name.length);
  if(document.cookie.indexOf(";",startPos) == -1){
    return document.cookie.substring(startPos,document.cookie.length);
  }
  else{
    return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos));
  }
return null;
}


//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal, 
//if there is a cookie then return;
//The cookie should expire in one day. 
function checkCookie() {
   var showed = getCookie("showed");
   if (showed != null && showed != "") {
      var date = new Date(showed).getDate();
      var currentDate = new Date().getDate();

      if (currentDate > date) {
          return true;
      }
       return false;
   }
    return true;
}

在设置cookie时, 使用

setCookie('showed',new Date().toGMTString(),1);

因为我们使用的是cookie值,而不是cookie的过期时间。所以值必须是日期字符串