Javascript cookie不适用于所有页面

时间:2014-01-26 18:16:18

标签: javascript jquery cookies

直播网站 - http://chitrchatr.com

我在退出按钮上成功添加了setCookie功能。另一个链接。因此,如果有人关闭弹出窗口或点击该链接,那么cookie将被存储& popup永远不会出现在他/她身上。

它工作得很好,我关闭/去链接它,它存储cookie,但当我尝试去另一个页面/链接的网站,它再次出现(cookie已经存储,但它上诉)。任何想法如何解决它,以便在存储cookie后,如果有人转到另一个页面,它将永远不会出现。

我的HTML -

<div id="popupBox">
 <div id='popupContent' class='visiblebox' style='width:500px;height:446px;z-index:999999;left: 31%; top: 15%;'>
 <a onClick="document.getElementById('popupBox').style.display='none'; setCookie('abc', 'def', 1)" href='#' id='closebox' title='Close this box'>X</a>
.... 
PopUp content here
....
<a onClick="document.getElementById('popupBox').style.display='none'; setCookie('abc', 'def', 1)" href="http://chitrchatr.com/signup-and-win-new-smartphones-and-get-our-service-for-free/" target="_blank"><img class="alignnone size-full wp-image-1548" alt="Promotion_06" src="http://chitrchatr.com/wp-content/uploads/2014/01/Promotion_06.png" width="243" height="61" /></a>
 </div>
</div>

使用Javascript -

    <script type="text/javascript">

        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 c_value = document.cookie;
        var c_start = c_value.indexOf(" " + c_name + "=");
        if (c_start == -1)
          {
          c_start = c_value.indexOf(c_name + "=");
          }
        if (c_start == -1)
          {
          c_value = null;
          }
        else
          {
          c_start = c_value.indexOf("=", c_start) + 1;
          var c_end = c_value.indexOf(";", c_start);
          if (c_end == -1)
          {
        c_end = c_value.length;
        }
        c_value = unescape(c_value.substring(c_start,c_end));
        }
        return c_value;
        }


        if(getCookie('abc')=="def" && document.getElementById('popupBox'))
        document.getElementById('popupBox').style.display='none';
</script>

2 个答案:

答案 0 :(得分:2)

添加Cookie的路径

function setCookie(name, value, days, secure) {
  var expires = '';
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    expires = '; expires='+date.toGMTString();
  }
  var domain = locDomain;
  document.cookie = name + '='+escape(value) + expires + '; path=/' + (domain ? '; domain=.' + domain : '') + ((secure && locProtocol == 'https:') ? '; secure' : '');
}

答案 1 :(得分:1)

尝试将Cookie的位置设置为“/”