我正在使用Javascript构建日历。这是我的第一个项目,我偶然发现了一个问题。 日历正文,即行和列,不会显示。我使用DOM在HTML中构建表格。
我的经验很少,但我无法弄清楚为什么Calendar.prototype.generateHTML()不起作用。
我真的很感激任何帮助,我已经坚持了一段时间。
window.onload = function () {
initMonths();
createYears();
initPrevButton();
Calendar(0,1990);
Calendar.prototype.generateHTML();
}
//globals
let currentDate = new Date();
let WEEK_DAYS = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];
let MONTHS = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
let MONTHS_DURATIONS = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let START_YEAR = 1990;
let END_YEAR = 2020;
let thead = document.getElementsByTagName('thead');
// Header
function initMonths() {
let select = document.getElementsByTagName('select')[0];
MONTHS.forEach(function(current, index, arr) {
let option = document.createElement('option');
option.innerHTML = current;
select.appendChild(option);
});
}
function createYears() {
let select = document.getElementsByTagName('select')[1];
for (var i = START_YEAR; i <= END_YEAR; i++) {
let option = document.createElement('option');
option.innerHTML = i;
select.appendChild(option);
}
}
function initPrevButton() {
let prevButton = document.getElementsByTagName('button')[0];
prevButton.addEventListener('click', function(index) {
MONTHS[index] = MONTHS[index - 1];
});
}
// body
function Calendar(month, year) {
this.month = (isNaN(month) || month == null) ? currentDate.getMonth() : month;
this.year = (isNaN(year) || year == null) ? currentDate.getFullYear() : year;
}
Calendar.prototype.generateHTML = function() {
let firstDay = new Date(this.year, this.month, 1);
let startingDay = firstDay.getDay();
let monthLength = MONTHS_DURATIONS[this.month];
if (this.month == 1) {
if (this.year % 4 === 0 && this.year % 100 != 0 || this.year % 400 === 0) {
monthLength = 29;
}
}
function generateRows() {
let day = 1;
//rows
for (let i = 0; i < 5; j++) {
//columns
for (let j = 0; j <= 6; j++) {
let tbody = document.getElementById('tableBody');
let createRow = document.createElement('tr');
let createCell = document.createElement('td');
if (day <= monthLength && (i > 0 && j >= startingDay)) {
createCell.innerHTML = day;
createRow.appendChild(createCell);
day++;
}
tbody.appendChild(createRow);
if(day > monthLength) {
break;
}
}
}
}
}