javascript - 无法显示上次访问日期

标签 javascript cookies

以下是用于存储用户上次访问网页的时间、日期的脚本。但是当我使用该脚本运行 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 标记设置时间/日期?脚本有什么问题?

最佳答案

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
}

关于javascript - 无法显示上次访问日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7529307/

相关文章:

javascript - 内联数组注释 DI 与 AngularJS 中的 $routeProvider 不兼容吗?

javascript - 类型错误 : 'undefined' is not an object (evaluating '$.fn' ) - Wordpress & shuffle. js

c# - 将 C# 变量传输到 aspx javascript 值时遇到困难

javascript - 使用 jspdf 将图像 url 转换为 pdf

javascript - Google Analytics JS 跟踪器设置的重复 cookie

javascript - 从 jQuery 设置 cookie 并从 php 读取的正确方法

java - 在 Java 代码中接受 Cookies?

javascript - 最大化 dijit 布局 BorderContainer

google-chrome - Chrome开发者工具>资源>cookies>http栏,这里的复选标记是否表示HttpOnly cookie?

ASP.NET 用户配置文件与使用 Cookie