gpt4 book ai didi

javascript - 尝试用js创建日历表

转载 作者:行者123 更新时间:2023-12-03 00:20:48 26 4
gpt4 key购买 nike

我的任务是显示日历 I js。所以得到了该月的第一天,并尝试使用下面代码中描述的逻辑制作一个表格。由于某种原因,下面的代码除了表头之外不打印任何内容。

var year = parseFloat(prompt("Enter Year: "))
var month = parseFloat(prompt("Enter Month in number: "))
var firstDay = (new Date(year, month)).getDay();
showcalander(firstDay);

function showcalander(day) {
tbl = document.getElementById("calendar-body").innerHTML = "";
let date = 1;
for (i = 1; i <= 5; i++) {
let row = document.createElement("tr");
for (j = 1; j <= 7; j++) {
if (i == 1 && j < day) {
cell = document.createElement("td");
cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
} else if (date > 30) {
break;
} else {
cell = document.createElement("td");
cellText = document.createTextNode(date);
cell.appendChild(cellText);
row.appendChild(cell);
date++;
}

}
tbl.appendChild(row);
}
}
<table id="calendar">
<thead>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
</thead>
<tbody id="calendar-body"></tbody>
</table>

最佳答案

问题出在这一行:

tbl = document.getElementById("calendar-body").innerHTML = ""

应该是:

tbl = document.getElementById("calendar-body")

var year = parseFloat(prompt("Enter Year: "))
var month = parseFloat(prompt("Enter Month in number: "))
var firstDay = (new Date(year, month)).getDay();
showcalander(firstDay);

function showcalander(day) {
tbl = document.getElementById("calendar-body");
let date = 1;
for (i = 1; i <= 5; i++) {
let row = document.createElement("tr");
for (j = 1; j <= 7; j++) {
if (i == 1 && j < day) {
cell = document.createElement("td");
cellText = document.createTextNode("");
cell.appendChild(cellText);
row.appendChild(cell);
} else if (date > 30) {
break;
} else {
cell = document.createElement("td");
cellText = document.createTextNode(date);
cell.appendChild(cellText);
row.appendChild(cell);
date++;
}

}
tbl.appendChild(row);
}
}
<table id="calendar">
<thead>
<tr>
<th>Sun</th>
<th>Mon</th>
<th>Tue</th>
<th>Wed</th>
<th>Thu</th>
<th>Fri</th>
<th>Sat</th>
</tr>
</thead>
<tbody id="calendar-body"></tbody>
</table>

关于javascript - 尝试用js创建日历表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54322873/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com