我正在尝试使用一小部分JavaScript来显示新年前夜剩下的天数。但是,我无法在网页上显示任何内容。我将包括我试图使用的HTML和库,如果有人能指出我正确的方向我会很感激。我的印象是HTML能够理解Date()函数,但我的老师告诉我,我必须删除它们才能使代码正常工作?
<!-- Days until New Year's Eve -->
<td id="daycell">
<!-- Add script tag and declare variables and assign values -->
<script>
var Today = new(Date);
var ThisDay = Today.getDate();
var ThisMonth = Today.getMonth();
var ThisYear = Today.getFullYear();
var DaysLeft = NYEdays(Today);
var MonthTxt = new Array("", "January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December");
<!-- Add date output statement -->
document.write("Today is" + MonthTxt[ThisMonth] + " " + ThisDay + ", " + ThisYear + ".");
<!-- Add decision statement for number of days -->
<script type = "text/javascript">
if (DaysLeft == 0) {
document.write("Today is New Years Eve!");
}
else {
document.write("Only" + DaysLeft "days until New Years Eve!");
}
</script>
这是library.js代码:
function NYEDays(CheckDay) {
var XYear=CheckDay.getFullYear();
var XDay=new Date("December, 31, 2015");
XDay.setFullYear(XYear);
var DayCount=(XDay-CheckDay)/(1000*60*60*24);
DayCount=Math.round(DayCount);
return DayCount;
}
我必须使用变量Today,ThisDay,ThisMonth,ThisYear,DaysLeft和MonthTxt作为数组。
答案 0 :(得分:0)
我重构了你的代码。这是JSFiddle:https://jsfiddle.net/vytfeq8k/
HTML:
<!-- Used divs instead of td as td needs to be within a table -->
<div id="curDate"></div>
<div id="daycell"></div>
的Javascript:
<script type="text/javascript">
// removed many unneeded variables
var curDate = new(Date);
var daysLeft = nyeDays(curDate);
// Fixed your array, you had an empty string as the first element so it would always return the previous month in the output
var monthTxt = new Array("January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December");
// Added another div instead of using document.write
$('#curDate').text("Today is " + monthTxt[curDate.getMonth()] + " " + curDate.getDate() + ", " + curDate.getFullYear() + ".");
// Same for this bit
if (daysLeft != 0) {
$('#daycell').text('Only ' + daysLeft + " days until New Years Eve");
} else {
$('#daycell').text('Today is New Years Eve');
}
// Refactored this
function nyeDays(checkDay) {
var nye = new Date("December, 31, 2015");
var dayCount = (nye - checkDay) / (1000*60*60*24);
return Math.round(dayCount);
}
</script>