用javascript写一个动态日历表,第1行为1-31号日期,第1列为人名,最后一列为 总值班天数,中间为可打钩矩形小框。最后的总值班天数为这一行打钩的天数和
时间: 2024-03-15 21:46:34 浏览: 22
好的,我可以为你提供一个简单的实现。以下是基于HTML、CSS和JavaScript的动态日历表代码:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<title>动态日历表</title>
<style>
table {
border-collapse: collapse;
}
td,
th {
border: 1px solid black;
width: 30px;
height: 30px;
text-align: center;
}
.checkbox {
width: 20px;
height: 20px;
margin: 5px;
cursor: pointer;
}
.checked {
background-color: black;
}
</style>
</head>
<body>
<table>
<thead>
<tr>
<th></th>
<th>1</th>
<th>2</th>
<th>3</th>
<th>4</th>
<th>5</th>
<th>6</th>
<th>7</th>
<th>8</th>
<th>9</th>
<th>10</th>
<th>11</th>
<th>12</th>
<th>13</th>
<th>14</th>
<th>15</th>
<th>16</th>
<th>17</th>
<th>18</th>
<th>19</th>
<th>20</th>
<th>21</th>
<th>22</th>
<th>23</th>
<th>24</th>
<th>25</th>
<th>26</th>
<th>27</th>
<th>28</th>
<th>29</th>
<th>30</th>
<th>31</th>
<th>总值班天数</th>
</tr>
</thead>
<tbody id="table-body">
<tr>
<td>小明</td>
</tr>
<tr>
<td>小红</td>
</tr>
<tr>
<td>小李</td>
</tr>
<tr>
<td>小张</td>
</tr>
</tbody>
</table>
<script>
const tableBody = document.getElementById("table-body");
// 创建打勾的checkbox元素
function createCheckbox() {
const checkbox = document.createElement("div");
checkbox.classList.add("checkbox");
checkbox.addEventListener("click", function () {
if (this.classList.contains("checked")) {
this.classList.remove("checked");
} else {
this.classList.add("checked");
}
updateTotalDays();
});
return checkbox;
}
// 更新总值班天数
function updateTotalDays() {
const rows = tableBody.querySelectorAll("tr");
rows.forEach((row) => {
const checkboxes = row.querySelectorAll(".checkbox");
let total = 0;
checkboxes.forEach((checkbox) => {
if (checkbox.classList.contains("checked")) {
total++;
}
});
const totalCell = row.lastElementChild;
totalCell.textContent = total;
});
}
// 创建行
function createRow(name) {
const row = document.createElement("tr");
const nameCell = document.createElement("td");
nameCell.textContent = name;
row.appendChild(nameCell);
for (let i = 0; i < 31; i++) {
const checkbox = createCheckbox();
const cell = document.createElement("td");
cell.appendChild(checkbox);
row.appendChild(cell);
}
const totalCell = document.createElement("td");
totalCell.textContent = 0;
row.appendChild(totalCell);
return row;
}
// 初始化表格
function initTable() {
const names = ["小明", "小红", "小李", "小张"];
names.forEach((name) => {
const row = createRow(name);
tableBody.appendChild(row);
});
}
initTable();
</script>
</body>
</html>
```
这段代码会生成一个表格,其中第一列是人名,第一行是日期,中间是可打钩的小框,最后一列是每个人的总值班天数。当用户点击一个小框时,它会变成打勾状态,并更新该行的总值班天数。