Cookie expiration date

2020-02-26 06:12发布

I am not a programmer. I am trying to use a cookie script that remembers the last drop down menu selection.

I found a script that works but it does only a session cookie. How do I add an expiration date to the cookie in this script?

<head>
  <script>        
    function SETcookie() {
      document.cookie = "Selected=" + document.getElementById('myList').selectedIndex;
    }

    function GETcookie() {
      if (document.cookie) {
        eval(document.cookie);
        document.getElementById('myList').selectedIndex = Selected;
      }
    }    
  </script>
</head>

<body onLoad="GETcookie()">
  <select id="myList" onChange="SETcookie()">
    <option value="1">Option 1</option>
    <option value="2">Option 2</option>
    <option value="3">Option 3</option>
    <option value="4">Option 4</option>
  </select>
</body>

7条回答
smile是对你的礼貌
2楼-- · 2020-02-26 06:56

Here's function which is 100% working and has no depreciated functions.

function setCookie(variable, value, expires_seconds) {
    var d = new Date();
    d = new Date(d.getTime() + 1000 * expires_seconds);
    document.cookie = variable + '=' + value + '; expires=' + d.toGMTString() + ';';
}
查看更多
登录 后发表回答