
本文详解 jquery 实现月度日历时“仅显示第一行”的典型逻辑缺陷,指出核心原因是循环未覆盖整月天数及周单元格管理错误,并提供结构清晰、可直接运行的修复方案。
本文详解 jquery 实现月度日历时“仅显示第一行”的典型逻辑缺陷,指出核心原因是循环未覆盖整月天数及周单元格管理错误,并提供结构清晰、可直接运行的修复方案。
在使用 JavaScript(配合 jQuery)动态生成 HTML 日历时,一个高频陷阱是:日历表格只渲染出第一行(即首周),其余日期完全缺失。问题并非出在 DOM 插入或 CSS 样式,而在于日期遍历逻辑与表格行( 原始代码中,for (var day = 0; day 单元格,无论当月实际有多少天(28–31 天)。更关键的是,$row.append(...) 后虽有 $calendarTable.append($row),但新行 $row = $(' 以下是经过重构的健壮实现,逻辑分三阶段清晰展开: 我们弃用脆弱的 day 通过以上重构,日历将稳定输出完整的 4–6 行(取决于当月起始日与天数),每行严格 7 列,首尾空白单元格自动补齐,真正实现符合现实日历逻辑的渲染效果。)生命周期管理的严重错位。
') 仅在特定条件(如 day === 6)下创建,且缺乏对剩余空白单元格(月末补位)的系统性处理,最终造成后续周次彻底丢失。
✅ 步骤一:预置基础信息与头部渲染
"use strict";
const months = ["January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December"];
// 封装获取当月最后一天的函数(注意:必须传入 year,避免跨年错误)
const getLastDayofMonth = (year, month) => new Date(year, month + 1, 0).getDate();
$(document).ready(function() {
const currentDate = new Date();
const currentMonth = currentDate.getMonth();
const currentYear = currentDate.getFullYear();
const monthName = months[currentMonth];
$('#month_year').text(`${monthName} ${currentYear}`);
const firstDayOfWeek = new Date(currentYear, currentMonth, 1).getDay(); // 0=Sun, 6=Sat
const lastDay = getLastDayofMonth(currentYear, currentMonth);
✅ 步骤二:构建完整日历表格体(核心修复区)
。 const $calendarTable = $('#calendar tbody'); // 指向 tbody 提升语义与性能
let $row = $('<tr>');
let currentWeekDay = firstDayOfWeek;
// Step 1: Add leading empty cells (before the 1st)
for (let i = 0; i ');
}
// Step 2: Add all calendar days (1 to lastDay)
for (let day = 1; day ${day}`);
currentWeekDay++;
// Trigger row append when week ends (Sunday) OR it's the last day
if (currentWeekDay % 7 === 0 || day === lastDay) {
// If ending on lastDay and row isn't full, pad with empty cells
if (day === lastDay && currentWeekDay % 7 !== 0) {
const trailingCount = 7 - (currentWeekDay % 7);
for (let i = 0; i ');
}
}
$calendarTable.append($row);
$row = $('</tr><tr>'); // Reset for next week
}
}
});<h3>✅ 步骤三:HTML 与 CSS 建议(增强健壮性)</h3>
<ul><li>
<strong>HTML 结构优化</strong>:显式声明 <thead> 和 </thead>
<tbody>,符合语义化标准,也便于 CSS 定位与未来扩展(如添加事件代理)。<li>
<strong>CSS 补充建议</strong>(calendar.css):<pre class="brush:php;toolbar:false;">#calendar {
border-collapse: collapse;
width: 100%;
max-width: 500px;
margin: 1rem auto;
}
#calendar th, #calendar td {
border: 1px solid #ccc;
padding: 8px 12px;
text-align: center;
}
#calendar th {
background-color: #f5f5f5;
font-weight: bold;
}
⚠️ 关键注意事项
,防止意外覆盖 ;
Java免费学习笔记:立即使用
解锁 Java 大师之旅:从入门到精通的终极指南










