如何使用jQuery按重复规则计算项目提醒日期并渲染为HTML表格
项目提醒功能解决方案
原有代码问题梳理
- 重复定义函数:
getPaymentPlan放在for循环内部,每次遍历都会重复创建,浪费性能 - 计算基准日期错误:固定使用
new Date("2021-01-01")作为计算起点,没有使用每个项目自带的start_date字段 - 周期匹配失败:数据库返回的
period_type为Yearly/Monthly首字母大写格式,代码内switch判断用全小写,匹配不到对应周期逻辑 - 多余日期计算:数据库返回的
start_date已经是提前了reminder_set_days的提醒基准日期,原有代码额外再减一次daysBefore,导致日期计算错误 - 缺少区间过滤:没有筛选出落在用户选择的起始日期之后的提醒记录
- 无结果汇总逻辑:没有把所有项目的提醒记录汇总,也没有渲染到HTML表格
前置准备(HTML部分)
首先页面需要有对应表格容器用来展示结果:
<!-- 搜索区域 --> <input type="date" id="fromdate_recu_view"> <input type="date" id="todate_recu_view"> <button id="find_recurrence">搜索</button> <input type="hidden" id="getID_comp" value="你的公司ID"> <!-- 结果表格 --> <table id="reminderTable" border="1" cellpadding="8" cellspacing="0"> <thead> <tr> <th>project Title</th> <th>reminderdate</th> </tr> </thead> <tbody> </tbody> </table>
修正后完整JS代码
$('#find_recurrence').click(function(event) { // 获取用户输入参数 const getID_comp = $('#getID_comp').val(); const fromDateVal = $('#fromdate_recu_view').val(); const toDateVal = $('#todate_recu_view').val(); // 转成Date对象方便后续比较 const userFromDate = new Date(fromDateVal); const userToDate = new Date(toDateVal); // 存储所有符合条件的提醒记录 const allReminders = []; // 把公共计算函数提到循环外面,只定义一次 const getPaymentPlan = ({projectTitle, baseDate, maxEndDate, period, skip, filterStartDate}) => { const recurrenceList = []; // 计算当前周期的提醒日期,直接用项目自带的start_date作为基准,不需要再减天数 let currentRemindDate = new Date(baseDate.getTime()); while (currentRemindDate.getTime() <= maxEndDate.getTime()) { // 只保留大于等于用户选的起始日期的记录 if (currentRemindDate.getTime() >= filterStartDate.getTime()) { recurrenceList.push({ title: projectTitle, date: currentRemindDate.toISOString().split('T')[0] }); } // 转小写匹配周期类型 switch (period.toLowerCase()) { case 'monthly': currentRemindDate.setMonth(currentRemindDate.getMonth() + Number(skip)); break; case 'yearly': currentRemindDate.setFullYear(currentRemindDate.getFullYear() + Number(skip)); break; default: console.log('wrong period type is given'); break; } } return recurrenceList; } $.ajax({ url: base_url + "index.php/welcome/list_all_projects_reminder/", type: "POST", data: { "company_id": getID_comp }, success: function(data) { const new_data = JSON.parse(data); // 清空之前的表格内容 $('#reminderTable tbody').empty(); // 遍历所有项目 new_data.projectremindshow.forEach(project => { // 传入当前项目的参数生成提醒列表 const projectReminders = getPaymentPlan({ projectTitle: project.project_title, baseDate: new Date(project.start_date), maxEndDate: userToDate, period: project.period_type, skip: project.recur_every, filterStartDate: userFromDate }); // 把当前项目的提醒合并到总列表 allReminders.push(...projectReminders); }); // 渲染到表格 allReminders.forEach(item => { const row = `<tr> <td>${item.title}</td> <td>${item.date}</td> </tr>`; $('#reminderTable tbody').append(row); }); } }); });
功能说明
- 完全匹配你给出的两个预期输出示例,自动按周期生成对应区间内的所有提醒日期
- 自动处理周期大小写匹配问题,支持年/月两种重复类型
- 自动过滤用户选择的起止区间,不会出现范围外的提醒记录
- 性能优化:公共函数只定义一次,最后一次性渲染表格,避免频繁操作DOM
内容的提问来源于stack exchange,提问作者Remesh sree
相关产品推荐
相关产品推荐

