我正在开展一个小项目,我必须显示当前日期。我需要添加nth
,st
等等,具体取决于变量字符串的最后一个字母,但是当我在Web浏览器中检查HTML文件时,字符串不会显示。这是我的代码:
window.onload = function() {
startDate();
}
function startDate() {
var month = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
var weekDay = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
var date = today.getDate();
date = checkDate(date);
document.getElementById("date").innerHTML = weekDay[today.getDay()] + " the " + date + " of " + month[today.getMonth()];
}
function checkDate(i) {
if (i.slice(-1) == 1 && i !== 11) {
i = i + "st";
} else if (i.slice(-1) == 2 && i !== 12) {
i = i + "nd";
} else if (i.slice(-1) == 3 && i !== 13) {
i = i + "rd";
} else {
i = i + "th";
}
return i;
}
这是我的HTML:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="container">
<div id="date"></div>
</div>
<script src="script.js"></script>
</body>
</html>
答案 0 :(得分:1)
您的代码存在一些问题。首先,你如何定义'今天'?其次,切片功能未在Number对象上定义。通过这两个编辑您的工作代码:
window.onload = function() {
startDate();
};
function startDate() {
var month = [
"January",
"February",
"March",
"April",
"May",
"June",
"July",
"August",
"September",
"October",
"November",
"December"
];
var weekDay = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
var today = new Date();
var date = today.getDate();
date = checkDate(String(date));
document.getElementById("date").innerHTML = weekDay[today.getDay()] + " the " + date + " of " + month[today.getMonth()];
}
function checkDate(i) {
if (i.slice(-1) == 1 && i !== 11) {
i = i + "st";
} else if (i.slice(-1) == 2 && i !== 12) {
i = i + "nd";
} else if (i.slice(-1) == 3 && i !== 13) {
i = i + "rd";
} else {
i = i + "th";
}
return i;
}
答案 1 :(得分:0)
您需要在使用之前定义today
,如下所示:
var today = new Date();
var date = today.getDate();
函数checkDate
接收数字参数,但后来使用slice
将其视为字符串:这会产生错误。您应该将其视为一个数字,例如i % 10
:
function checkDate(i) {
return (i % 10 == 1 && i !== 11) ? i + "st"
: (i % 10 == 2 && i !== 12) ? i + "nd"
: (i % 10 == 3 && i !== 13) ? i + "rd"
: i + "th";
}