我有以下代码。我在这行`var datemsg = nameOfMonths [date.getMonth()] +“”+ date.getDate();中得到一个未定义或错误。
如果我只使用var date = new Date();
,则会在HTML页面上打印这些值。但是使用我打算在下面使用getCookie("date")
使用的代码来从浏览器中获取日期。它给了我一个错误,它不会打印日期和时间。
<body onload="setsaveCookie(); loadSaveCookies()">
<h1 class="header">Welcome your visit started on <span id="date"></span> at <span id="time"></span> <span id="ampm"></span></h1>
function setsaveCookie() {
var date = new Date();
setCookie("date", date, 30);
getDate();
}
function setCookie(cookieName, cookieValue, expires) {
var date = new Date();
date.setTime(date.getTime() + (expires * 24 * 60 * 60 * 1000));
var dayexpires = "expires=" + date.toGMTString();
document.cookie = cookieName + "=" + cookieValue + ";" + dayexpires + ";path=/";
var msg = "";
}
function getDate() {
var date = new Date();
var nameOfMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"]
var ampm = "";
var date = getCookie("date");
var twelvehourtime = "";
var datemsg = nameOfMonths[date.getMonth()] + " " + date.getDate();
document.getElementById("date").innerHTML = datemsg;
}
function getCookie(cookieName) {
var name = cookieName + "=";
var decodedCookie = decodeURIComponent(document.cookie);
var ca = decodedCookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') {
c = c.substring(1);
}
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length);
}
}
return "";
}
答案 0 :(得分:0)
以下是getDate函数的修订版本。
function getDate() {
var nameOfMonths = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "July", "Aug", "Sep", "Oct", "Nov", "Dec"]
var ampm = "";
var date = getCookie("date");
var dt = new Date(date);
var twelvehourtime = "";
var datemsg = nameOfMonths[dt.getMonth()] + " " + dt.getDate();
document.getElementById("date").innerHTML = datemsg;
}