简体   繁体   English

如何在Javascript中设置Cookie的到期日期

[英]How to set a cookie's expiration date in Javascript

I am trying to make a cookie that expires on a specific date. 我正在尝试制作一个在特定日期到期的cookie。 On w3schools they said to set it using 他们说在w3schools使用

document.cookie="mediaType=Video; expires=Fri, 13 Mar 2015 12:00:00 UTC";

However in my code it doesn't seem to be working. 但是在我的代码中,它似乎不起作用。 What am I doing wrong? 我究竟做错了什么?

<script>
    var mediaType = "image";
    function checkCookies(){
            document.getElementById("div").innerHTML = document.cookie;
    }
    function getType() {
        document.cookie="mediaType=Video; expires=Fri, 13 Mar 2015 12:00:00 UTC";
        document.getElementById("div").innerHTML = document.cookie
    }
</script>

<body onload="checkCookies()">
    <select onChange="mediaType = this.value">
      <option value="image">Image</option>
      <option value="link">Link</option>
      <option value="text">Text</option>
    </select>
</body>

<div id="div" onclick="getType()"> hi</div>

BONUS is there a way to set a cookie as the value of a variable? 奖金有办法将Cookie设置为变量的值吗?

The method you are using for setting the cookie is correct but at start the values are not showing because there are no cookies. 您用于设置Cookie的方法是正确的,但由于没有cookie,因此开始时未显示值。 Remember that you only can access the cookies set by your site so at start there aren't any. 请记住,您只能访问由您的网站设置的cookie,因此一开始没有任何cookie。 You can add a test cookie to see that your code is working like in the following example, also it shows how to update the value of the cookie when the select is changed as you asked: 您可以添加一个测试cookie,以查看您的代码是否如以下示例所示正常工作,还显示了如何根据您的要求更改选择内容时更新cookie的值:

<script>
function checkCookies(){
    document.cookie="Test=Test Cookie; expires=Fri, 13 Mar 2015 12:00:00 UTC";
    document.getElementById("div").innerHTML = document.cookie;
}
function updateCookies(val) {
    document.cookie="mediaType="+ val +"; expires=Fri, 13 Mar 2015 12:00:00 UTC";
    document.getElementById("div").innerHTML = document.cookie;
}
</script>

<body onload="checkCookies()">
  <select onChange="updateCookies(this.value)">
    <option value="image">Image</option>
    <option value="link">Link</option>
    <option value="text">Text</option>
  </select>

  <div id="div"> hi</div>

</body>

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

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