每日簽到是提升用戶留存的經典功能。本文完整解析一套基於 jQuery 的簽到日曆實作:calendar.js (核心邏輯)、sign.css (樣式)、sign.jsp (後端整合入口),涵蓋日曆渲染、簽到狀態標記、數據交互全流程。
var calUtil = {
// 取得某年某月天數
getDaysInmonth: function(iMonth, iYear) {
return new Date(iYear, iMonth, 0).getDate(); // 第 0 天 = 上月最後一天
},
// 建構月曆二維陣列 [週][日] (0-based 週, 0=週日)
bulidCal: function(iYear, iMonth) {
const aMonth = Array.from({length: 7}, () => new Array(7));
const firstDay = new Date(iYear, iMonth - 1, 1).getDay(); // 0-6
const daysInMonth = this.getDaysInmonth(iMonth, iYear);
// 表頭
aMonth[0] = ['日','一','二','三','四','五','六'];
let day = 1;
// 第一週:從 firstDay 開始填
for (let d = firstDay; d < 7; d++) aMonth[1][d] = day++;
// 後續週
for (let w = 2; w < 7; w++) {
for (let d = 0; d < 7; d++) {
if (day <= daysInMonth) aMonth[w][d] = day++;
}
}
return aMonth;
},
// 檢查某天是否已簽到
ifHasSigned: function(signList, day) {
return signList.some(item => item.signDay === day);
},
// 渲染 HTML
drawCal: function(iYear, iMonth, signList) {
const myMonth = this.bulidCal(iYear, iMonth);
const htmls = [];
htmls.push("");
htmls.push("");
htmls.push("" + iYear + "年" + String(iMonth).padStart(2,'0') + "月");
htmls.push("");
htmls.push("");
myMonth[0].forEach(day => htmls.push("" + day + " "));
htmls.push(" ");
for (let w = 1; w < 7; w++) {
htmls.push("");
for (let d = 0; d < 7; d++) {
const dayNum = myMonth[w][d];
const signed = dayNum && this.ifHasSigned(signList, dayNum);
htmls.push("" + (dayNum || ' ') + " ");
}
htmls.push(" ");
}
htmls.push("
");
return htmls.join('');
}
};
.sign_main { width: 400px; border-top: 1px solid #e3e3e3; font-family: "Microsoft YaHei", SimHei; display: none; }
.sign_succ_calendar_title { text-align: center; width: 398px; border-left: 1px solid #e3e3e3; border-right: 1px solid #e3e3e3; background: #fff; }
.calendar_month_span { display: inline; line-height: 40px; font-size: 16px; color: #656565; letter-spacing: 2px; font-weight: bold; }
.sign table { border-collapse: collapse; width: 100%; }
.sign th, .sign td { width: 30px; height: 40px; text-align: center; line-height: 40px; border: 1px solid #e3e3e3; }
.sign th { font-size: 16px; }
.sign td { color: #404040; vertical-align: middle; }
.sign .on { background: url(images/sign_have.gif) no-repeat center; } /* 已簽到樣式 */
.sign_main { display: none; } /* 預設隱藏,由 JS 控制顯示 */
<%@ page contentType="text/html;charset=UTF-8" %>
<%
// 1. 取得當前用戶簽到記錄 (從 DB/Redis)
// List signList = signService.getSignRecords(userId, year, month);
// signList 格式: [{signDay: 1}, {signDay: 5}, ...]
// 2. 傳遞給前端 (JSON 嵌入或 API)
String signListJson = new Gson().toJson(signList);
%>
<html>
<head>
<link rel="stylesheet" href="sign.css">
<script src="jquery.min.js"></script>
<script src="calendar.js"></script>
</head>
<body>
<div id="signContainer"></div>
<script>
$(function() {
const signList = ${signListJson}; // JSP 模板引擎輸出
const now = new Date();
const html = calUtil.drawCal(now.getFullYear(), now.getMonth() + 1, signList);
$('#signContainer').html(html).show();
// 綁定簽到點擊事件 (委派)
$('#sign_cal').on('click', 'td:not(.on)', function() {
const day = parseInt($(this).text());
if (isNaN(day)) return;
$.post('/sign/doSign', { day }, function(res) {
if (res.success) {
$(this).addClass('on');
// 可顯示獎勵彈窗
} else {
alert(res.msg || '簽到失敗');
}
});
});
});
</script>
</body>
</html>
| 模式 | 體現位置 | 優勢 |
|---|---|---|
| 命名空間模組化 | var calUtil = { ... } | 避免全域污染,邏輯聚合 |
| 資料與視圖分離 | bulidCal 產生純資料陣列,drawCal 負責渲染 | 易測試、易替換模板引擎 |
| 委派事件 | $('#sign_cal').on('click', 'td', ...) | 動態新增天數無需重綁,效能佳 |
| 狀態類名驅動樣式 | .on 類名對應 CSS 背景圖 | 行為與外觀解耦 |
drawCal 並 AJAX 取得該月簽到資料。day < today 且未簽到,顯示「補簽」按鈕 (需消耗道具/金幣)。.on-vip、.on-normal。此實作展示了「工具物件 + 模板字串拼接 + jQuery 委派事件」的經典 jQuery 時代最佳實踐。現代重構建議:改用 Vue/React 組件化、狀態管理 (Pinia/Redux)、CSS Modules/Scoped CSS、Composition API 邏輯復用,核心演算法 (bulidCal) 可直接移植。