You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现Datatables默认加载当月数据,点击前后按钮切换月份查询

输入图片描述

可以实现,核心思路是通过自定义Datatable筛选函数结合按钮触发日期范围自动计算,无需用户手动输入日期即可完成月份切换筛选,具体实现步骤如下:

实现步骤

1. 定义基础变量与工具函数

首先定义全局变量存储当前选中的月份,以及计算指定年月起止时间的工具函数:

// 初始化默认选中当前月份
let currentYearMonth = new Date();

// 工具函数:获取指定年月的第一天0点和最后一天23:59:59的时间值,可根据自身日期字段格式调整输出
function getMonthRange(date) {
  const year = date.getFullYear();
  const month = date.getMonth();
  const firstDay = new Date(year, month, 1, 0, 0, 0).getTime();
  const lastDay = new Date(year, month + 1, 0, 23, 59, 59).getTime();
  return { firstDay, lastDay };
}

2. 配置Datatable自定义筛选规则

初始化Datatable前注册自定义筛选器,匹配日期字段落在当前月份范围内的条目:

// 注册全局筛选规则
$.fn.dataTable.ext.search.push(
  function(settings, data, dataIndex) {
    // 示例假设表格第3列为日期字段,索引从0开始,可根据实际列位置调整
    const rowDate = new Date(data[2]).getTime();
    const { firstDay, lastDay } = getMonthRange(currentYearMonth);
    return rowDate >= firstDay && rowDate <= lastDay;
  }
);

// 初始化Datatable,原有其他配置保持不变
const myTable = $('#yourTableId').DataTable({
  pageLength: 25, // 每页加载条数,可按需调整为50/100
  // 其他原有配置:列定义、排序规则等
});

3. 绑定上下月按钮点击事件

页面添加上下月按钮,绑定点击逻辑修改当前选中月份后触发表格重绘即可:

<button id="prevMonthBtn">上一月</button>
<button id="nextMonthBtn">下一月</button>

<script>
// 上一月切换
$('#prevMonthBtn').click(function() {
  currentYearMonth.setMonth(currentYearMonth.getMonth() - 1);
  myTable.draw();
});

// 下一月切换
$('#nextMonthBtn').click(function() {
  currentYearMonth.setMonth(currentYearMonth.getMonth() + 1);
  myTable.draw();
});
</script>
适配说明
  • 如果你的日期字段为字符串格式(如YYYY-MM-DD),只需调整getMonthRange的返回格式,以及行数据的日期转换逻辑即可匹配。
  • 若使用服务端分页模式,无需配置前端筛选,只需在按钮点击时将当前年月作为请求参数传给后端,由后端返回对应月份的分页数据即可。

内容的提问来源于stack exchange,提问作者Cheknov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.28 10:15:06