2011-09-23 85 views
0

以下是用於存儲時間和用戶上次訪問網頁的日期的腳本。但是,當我使用腳本運行HTML時,沒有任何反應。無法顯示上次訪問日期

window.onload = init; 

function init() { 
var now = new Date(); 
    var last = new Date(); 
document.cookie = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toGMTString() + ";lastVisit=" + last.toDateString(); 
var lastVisit = document.cookie.split("="); 
document.getElementById("lastVisitedOn").value = lastVisit[6]; 

} 

HTML

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title>Untitled Document</title> 
<script type="text/javascript" src="lastVisitTester.js"> 
</script> 
</head> 

<body> 
<form> 
<label>Enter your name&nbsp;&nbsp;<input type="text" id="name_field" /></label> <br/> 
<input type="submit" value="submit" /> 
</form> 
<h1 id="lastVisitedOn"></h1> 
</body> 
</html> 

爲什麼時間/日期沒有得到設置了h標籤?腳本有什麼問題?

回答

2
window.onload = function() { 
    var now   = new Date(), 
     expires  = now, 
     lastVisit = document.cookie.match(/lastVisit=([^;]+)/), 
     userName = 'somebody'; 
    // 1. You should set month in standalone way 
    expires.setMonth(now.getMonth() + 2); 
    // 2. For each cookie you set value individually: for username in 1st line, and for lastVisit in 2nd 
    document.cookie = "username=" + userName + ";path=/;expires=" + expires.toGMTString(); 
    document.cookie = "lastVisit=" + now.toDateString() + ";path=/;expires=" + expires.toGMTString(); 
    // 3. You should test and extract your cookie value BEFORE you set it (see above with cookie match) 
    // 4. You should test if it's not null also 
    if (null != lastVisit) { 
     // 5. You should use innerHTML property for set content 
     document.getElementById("lastVisitedOn").innerHTML = lastVisit[1]; 
    } 

    // 6. But in general you should RTFM more :) 
    // 7. ps: And also use some standard frameworks for this -- not manual raw JS 
} 
+0

@see http://www.quirksmode.org/js/cookies.html – gaRex

1

那麼在你的代碼中有一些問題。

正如其他之前提到:

  1. 函數 「toGMTString()」 已過時。而不是 「toGMTString()」

    使用 「的toLocaleString()」 或 「toUTCString()」(也https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date#toGMTString見)

  2. 你應該使用innerHTML,你有你的指數是錯誤的。
  3. 你不能以這種方式使用document.cookie。不確定的方式。

    實施例:

    var now = new Date(); 
    var last = new Date(); 
    var cookieText = "username=" + ";path=/;expires=" + now.setMonth(now.getMonth() + 2).toLocaleString() + ";lastVisit=" + last.toDateString(); 
    
    document.cookie = cookieText; 
    var lastVisit = cookieText .split("="); 
    document.getElementById("lastVisitedOn").innerHTML = lastVisit[4]; 
    
+0

它顯示未定義! –