使数据表总计行不受排序/筛选的影响



我正在使用jquery datatable。我还在最后 tr 中添加了总计。当我按日期范围或数据表默认搜索任何数据时,搜索我的总数未显示。如何使用搜索结果总数修复它?

这是我的脚本

$.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                    var min = $('#datepicker_from').datepicker("getDate");
                    var max = $('#datepicker_to').datepicker("getDate");
                    var startDate = new Date(data[1]);
                    if (min == null && max == null) {
                        return true;
                    }
                    if (min == null && startDate <= max) {
                        return true;
                    }
                    if (max == null && startDate >= min) {
                        return true;
                    }
                    if (startDate <= max && startDate >= min) {
                        return true;
                    }
                    return false;
                }
            );

            $("#datepicker_from").datepicker({
                onSelect: function () {
                    table.draw();
                },
                changeMonth: true,
                changeYear: true,
                autoclose: true,
                todayHighlight: true
            });
            $("#datepicker_to").datepicker({
                onSelect: function () {
                    table.draw();
                }, changeMonth: true,
                changeYear: true,
                autoclose: true,
                todayHighlight: true
            });
            var table = $('#datatable').DataTable();
            // Event listener to the two range filtering inputs to redraw on input
            $('#datepicker_from, #datepicker_to').change(function () {
                table.draw();
            });

考虑到您没有分享某些先决条件,我将允许自己编造自己的示例。

因此,如前所述,问题的最佳解决方案是将总计放入<tfoot>行中,这样它们就不会受到过滤或排序的影响:

//source data
const srcData = [
  {item: 'apple', order: '12/03/2019', cost: 15},
  {item: 'pear', order: '24/10/2018', cost: 24},
  {item: 'banana', order: '13/02/2019', cost: 14},
  {item: 'plum', order: '11/12/2018', cost: 26}
];
//DataTable initialization
const dataTable = $('#mytable').DataTable({
  dom: 't',
  data: srcData,
  columns: [
    {title: 'Item', data: 'item'},
    {title: 'Order date', data: 'order'},
    {title: 'Cost', data: 'cost'}
  ],
  drawCallback: () => {
	//append tfoot and populate it with total cost
	$('#mytable tfoot').remove();
	$('#mytable').append(`<tfoot><td colspan="3" style="text-align:right"><b>Total cost:</b> ${$('#mytable').DataTable().column(2, {search:'applied'}).data().toArray().reduce((sum, item) => sum+=item, 0)}</td></tfoot>`);
  }
});
//custom date range filter
$.fn.DataTable.ext.search.push((settings, row) => (new Date(row[1].split('/').reverse()) >= new Date($('#startdate').val().split('/')) || $('#startdate').val() == '') && 
	(new Date(row[1].split('/').reverse()) <= new Date($('#enddate').val().split('/')) || $('#enddate').val() == ''));
//bind 'from' / 'to' inputs
$('input[type="date"]').on('change', function(){
  if($(this).attr('id') == 'startdate') $('#enddate').attr('min', $(this).val());
  else if ($(this).attr('id') == 'enddate') $('#startdate').attr('max', $(this).val());
  dataTable.draw();
});
<!doctype html>
<html>
<head>
  <script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
  <script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
  <link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
  <label>from:</label>
  <input type="date" id="startdate"></input>
  <label>to:</label>
  <input type="date" id="enddate"></input>
  <table id="mytable"></table>
</body>
</html>

但是,如果出于某种原因,您希望将总计保留为<tbody>底部的常规行,则可以更改drawCallback以在每次重绘时附加总计行以确保总计行的持久性,或者将id属性附加到它并通过自定义过滤器传递总计行。

如果首选前者,您只需将drawCallback选项(回到我的示例(更改为:

  drawCallback: () => {
    //append row to tbody and populate it with total cost
    $('#mytable #totals').remove();
    $('#mytable tbody').append(`<td id="totals" colspan="3" style="text-align:right"><b>Total cost:</b> ${$('#mytable').DataTable().column(2, {search:'applied'}).data().toArray().reduce((sum, item) => sum+=item, 0)}</td>`);
  }

如果后一个选项更适合您,并且您使用 id="totals" 构造总计行,则过滤器(再次回到我的示例(将如下所示(注意最后一行(:

//custom date range filter
$.fn.DataTable.ext.search.push((settings, row, index) => (new Date(row[1].split('/').reverse()) >= new Date($('#startdate').val().split('/')) || $('#startdate').val() == '') && 
    (new Date(row[1].split('/').reverse()) <= new Date($('#enddate').val().split('/')) || $('#enddate').val() == '')) 
    || $(dataTable.row(index).node()).is('#totals');

最新更新