试图在js中创建一个calander表

时间:2019-01-23 08:27:15

标签: javascript jquery html

我被分配以显示日历js。因此获得了每月的第一天,并尝试使用以下代码中描述的逻辑制作表格。由于某种原因,下面的代码除了表头之外什么也不会打印。谁能告诉我我出了什么问题...提前Tnxs。

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>

1 个答案:

答案 0 :(得分:1)

问题是这条线:

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>