我正在尝试显示一个日历,其中月份和年份显示在顶部,而日期则在一行(数字行格式)的下方。我想在单击按钮后得到下一个和上一个月。
但是,它仅在单击一次后有效,我无法获得该月显示的正确天数。
var month = new Array();
month[0] = "January";
month[1] = "February";
month[2] = "March";
month[3] = "April";
month[4] = "May";
month[5] = "June";
month[6] = "July";
month[7] = "August";
month[8] = "September";
month[9] = "October";
month[10] = "November";
month[11] = "December";
var d = new Date();
var label = month[d.getMonth()];
var year = d.getFullYear();
var day = d.getDate();
document.getElementById("mon").innerHTML = label + " " + year;
document.getElementById("days").innerHTML = day;
//display days
var daysInMonths = [31, (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
document.getElementById("prevBtn").addEventListener("click", previousMonth);
function previousMonth() {
label = month[d.getMonth() - 1];
document.getElementById("mon").innerHTML = label + " " + year;
}
document.getElementById("nextBtn").addEventListener("click", nextMonth);
function nextMonth() {
label = month[d.getMonth() + 1];
if (label > 11) {
year = d.getFullYear() + 1;
}
document.getElementById("mon").innerHTML = label + " " + year;
}
<div class="calendar">
<div class="header">
<span class="left button" id="prevBtn">⟨</span>
<span><h1 id="mon"></h1></span>
<span class="right button" id="nextBtn">⟩</span>
</div>
<table>
<tbody>
<tr id="days"></tr>
</tbody>
</table>
</div>
答案 0 :(得分:0)
根据我上面的评论,我在下面做了一些修改。
var month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var today = new Date();
var label = month[today.getMonth()];
var mm = today.getMonth(); // keep track of the month
var year = today.getFullYear(); // keep track of the year
var day = today.getDate();
document.getElementById("mon").innerHTML = label + " " + year;
document.getElementById("days").innerHTML = day;
//display days
var daysInMonths = [31, (((year%4==0)&&(year%100!=0))||(year%400==0)) ? 29 : 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
document.getElementById("prevBtn").addEventListener("click", previousMonth);
function previousMonth() {
mm -= 1; // decrement the month
if (mm < 0) { // if we go before January
mm = 11; // go to December
year -= 1; // of previous year
}
label = month[mm];
document.getElementById("mon").innerHTML = label + " " + year;
}
document.getElementById("nextBtn").addEventListener("click", nextMonth);
function nextMonth(){
mm += 1; // increment month
if (mm > 11) { // if we go after December
mm = 0; // go to January
year += 1; // of next year
}
document.getElementById("mon").innerHTML = label + " " + year;
}