【问题标题】:Set cookie that expire after 1 hour instead of day设置 1 小时而不是一天后过期的 cookie
【发布时间】:2014-08-11 06:00:22
【问题描述】:

我已经有设置 cookie 有效期为 1 天的代码,但我想设置 cookie 在 1 小时而不是 1 天后过期。我怎样才能做到这一点?

HTML

<a href="#" onClick="setCookie('see', '000', 1);">Link</a>

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 + ";path=/";
        }

        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('see')=="000" && document.getElementById('stickyAds'))
        document.getElementById('stickyAds').style.display='none';
 </script> 

【问题讨论】:

标签: javascript cookies


【解决方案1】:

1 天是 24 小时,所以 1 小时是 1/24 天

<a href="#" onClick="setCookie('see', '000', 1/24);">Link</a>

这是你想要的吗?

【讨论】:

    【解决方案2】:
    function setCookie(c_name, value, exhours) {
        var exdate = new Date();
        var val = exdate.valueOf();
        val += 3600000 * exhours; // Add exhours * 3600000 milliseconds to the date
        exdate = new Date(val); 
        var c_value = escape(value) + ((exhours == null) ? "" : "; expires=" + exdate.toUTCString());
        document.cookie = c_name + "=" + c_value + ";path=/";
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-03-07
      • 2013-10-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      相关资源
      最近更新 更多