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

Datatable.js全选复选框事件监听:判断选中状态并更新全局变量

Datatable.js 全选复选框状态监听与全局变量更新方案

场景1:使用Datatable Select插件自带的全选复选框

Datatable的Select插件会自动生成表头全选框,可通过监听该复选框的change事件直接更新全局变量:

// 初始化带多选功能的Datatable
var table = $('#your-table-id').DataTable({
  select: {
    style: 'multi',
    selector: 'td:first-child' // 指定第一列为选择列
  }
});

// 获取插件生成的全选复选框
var globalCheckAll = $('th.dt-checkboxes-cell input[type="checkbox"]');

// 监听状态变化,更新全局变量
globalCheckAll.on('change', function() {
  checkAll = this.checked ? 1 : 0;
  // 可在此添加后续逻辑,比如根据checkAll值执行操作
});

场景2:自定义表头全选复选框

如果是自己手动在表头添加的全选框,直接监听其change事件即可:

<!-- 自定义表头全选框 -->
<thead>
  <tr>
    <th><input type="checkbox" id="custom-check-all"></th>
    <!-- 其他列定义 -->
  </tr>
</thead>
// 监听自定义全选框的状态变化
$('#custom-check-all').on('change', function() {
  checkAll = this.checked ? 1 : 0;
  // 可选:同步控制表格行的选中状态
  if (this.checked) {
    table.rows().select();
  } else {
    table.rows().deselect();
  }
});

补充:通过Datatable内置事件判断全选状态

如果需要基于表格选中行的数量判断是否全选(支持分页场景),可监听select/deselect事件:

table.on('select deselect', function(e, dt, type) {
  if (type === 'row') {
    // 判断当前页是否全选
    var selectedCurrent = dt.rows({ page: 'current', selected: true }).count();
    var totalCurrent = dt.rows({ page: 'current' }).count();
    // 或者判断所有页是否全选:dt.rows({ selected: true }).count() === dt.rows().count()
    checkAll = (selectedCurrent === totalCurrent) ? 1 : 0;
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 00:52:02