实现复选框状态持久化至每周一自动重置的待办清单
实现每周一自动重置的待办清单方案
核心思路是通过记录上次重置的日期,在页面加载时判断当前是否为周一且尚未完成本周重置,若满足条件则清空所有复选框状态并更新记录。
具体实现步骤
1. 新增日期处理与重置判断逻辑
需要两个辅助函数:
- 获取本周一的格式化日期(用于对比重置时间)
- 检查是否需要执行每周重置
2. 修改页面加载流程
页面加载时先判断是否需要重置,再恢复之前的勾选状态(如果不需要重置的话)。
3. 更新存储逻辑
重置时需要清空复选框状态,并更新localStorage中的记录,包括重置日期、复选框状态和按钮文本。
修改后的完整代码
// 获取本周一的格式化日期(YYYY-MM-DD) function getCurrentWeekMonday() { const now = new Date(); const day = now.getDay(); const diff = now.getDate() - day + (day === 0 ? -6 : 1); // 处理周日的边界情况 const monday = new Date(now.setDate(diff)); return monday.toISOString().split('T')[0]; } // 初始化存储数据 let formValues = JSON.parse(localStorage.getItem('formValues')) || {}; let lastResetDate = localStorage.getItem('lastResetDate') || ''; const $checkboxes = $("#checkbox-container :checkbox"); const $button = $("#checkbox-container button"); // 检查并执行每周重置 function checkWeeklyReset() { const currentMonday = getCurrentWeekMonday(); const today = new Date().toISOString().split('T')[0]; // 如果今天是本周一且尚未完成本周重置 if (currentMonday === today && lastResetDate !== currentMonday) { // 清空所有复选框状态 $checkboxes.prop("checked", false); // 更新formValues中的复选框状态 $checkboxes.each(function(){ formValues[this.id] = false; }); // 重置按钮文本 formValues["buttonText"] = "Check all"; // 更新本地存储 localStorage.setItem('formValues', JSON.stringify(formValues)); localStorage.setItem('lastResetDate', currentMonday); // 更新页面按钮显示 $button.text("Check all"); } } function allChecked(){ return $checkboxes.length === $checkboxes.filter(":checked").length; } function updateButtonStatus(){ $button.text(allChecked()? "Uncheck all" : "Check all"); } function handleButtonClick(){ $checkboxes.prop("checked", allChecked()? false : true) } function updateStorage(){ $checkboxes.each(function(){ formValues[this.id] = this.checked; }); formValues["buttonText"] = $button.text(); localStorage.setItem("formValues", JSON.stringify(formValues)); } $button.on("click", function() { handleButtonClick(); updateButtonStatus(); updateStorage(); }); $checkboxes.on("change", function(){ updateButtonStatus(); updateStorage(); }); // 页面加载流程:先检查重置,再恢复状态 checkWeeklyReset(); $.each(formValues, function(key, value) { $("#" + key).prop('checked', value); }); $button.text(formValues["buttonText"] || "Check all");
关键逻辑说明
getCurrentWeekMonday():计算本周一的日期,处理了周日的边界情况(周日时,本周一为前一周的周一)。checkWeeklyReset():对比当前日期和本周一,同时通过lastResetDate确保每周只重置一次,避免页面刷新重复触发重置操作。- 重置时会同步更新
localStorage中的所有状态数据,保证刷新页面后显示的状态一致。
内容的提问来源于stack exchange,提问作者BostonBB
相关产品推荐
相关产品推荐

