无法显示上次访问日期 [英] unable to display the last visited date

查看:97
本文介绍了无法显示上次访问日期的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是脚本,用于存储时间,用户上次访问网页的日期。当我使用脚本运行HTML时,没有任何反应。

Following is the script that is meant to store the time,date the user last visited a webpage.But nothing happens when i run the HTML with the script.

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 tag?

推荐答案

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
}

这篇关于无法显示上次访问日期的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆