2017-08-27 75 views
-1

在下面的代碼中,我嘗試製作一個持久cookie。該cookie已成功創建。它存儲在文本框中指定的名稱,並且當頁面被重新加載時,警告框以「welcome back nameFromTextBox」出現。但是,隨着瀏覽器會話結束,當我關閉瀏覽器並再次加載頁面時,Cookie被刪除。我想製作一個cookie,每當我打開頁面時它都會持續。這是我做這件事的正確方法嗎?少了什麼東西?Cookie未持續保存在javascript中

<html> 
<head> 
    <script> 
     window.onload = function() 
     { 
      if(document.cookie.length!=0) 
      { 
       var cook = document.cookie.split("="); 
       document.getElementById("txt").value=cook[1]; 
       alert("Welcome back " + cook[1]); 
      } 
     } 

     function mname() 
     { 
      var tdate = new Date(); 
      tdate.setDate(tdate.getDate()+1); 
      var uname = document.getElementById("txt").value; 
      document.cookie="name=" + uname + ";expires=tdate.toUTCString();"; 
      alert("cookie created as " + document.cookie); 
     } 
    </script> 
</head> 
<body> 
    Please enter your name-<br> 
    <input type="text" id="txt" /><br> 
    <button onclick="mname()">Submit</button> 
</body> 

+0

看看在你的問題中漂亮的顏色,這應該是顯而易見的爲什麼日期部分公司okie不工作 – adeneo

+0

爲什麼它不工作? @adeneo – trex1999

+1

因爲'tdate.toUTCString();'實際上是一個字符串**,所以它是紅色的,而不是上面代碼中的黑色。 – adeneo

回答

0

的問題是在這條線

document.cookie="name=" + uname + ";expires=tdate.toUTCString();"; 

校正

document.cookie="name=" + uname + ";expires=" + tdate.toUTCString(); 

和工程....