DataTables footerCallback - 以另一个单元

时间:2017-02-11 20:22:02

标签: javascript jquery datatables table-footer

我试图在DataTables中实现footerCallback,它根据同一行中不同列中的单元格计算每列的条件和。这是我的设置演示:https://jsfiddle.net/rantoun/552y9j90/13/

HTML:

<table id="table1">
  <thead>
    <tr>
      <th>Fruit</th>
      <th>sumCondition</th>
      <th># Eaten</th>
      <th># Remaining</th>
    </tr>
  </thead>
  <tfoot>
    <tr>
      <th></th>
      <th align="center">Count</th>
      <th align="left"></th>
      <th align="left"></th>
    </tr>
  </tfoot>
  <tbody>
    <tr>
      <td>Apples</td>
      <td>Use</td>
      <td>3</td>
      <td>8</td>
    </tr>
    <tr>
      <td>Oranges</td>
      <td>Use</td>
      <td>6</td>
      <td>5</td>
    </tr>
    <tr>
      <td>Bananas</td>
      <td>Ignore</td>
      <td>2</td>
      <td>9</td>
    </tr>
  </tbody>
</table>

jQuery的:

$("#table1").DataTable({
  "paging": false,
  "searching": false,
  "info": false,    
    "footerCallback": function ( row, data, start, end, display ) {

      var columns = [2, 3];
      var api = this.api();

      _.each(columns, function(idx) {

          var total = api
              .column(idx)
              .data()
              .reduce(function (a, b) {
                  return parseInt(a) + parseInt(b);
              }, 0)         

                $('tr:eq(0) th:eq('+idx+')', api.table().footer()).html(total);
      })

  }
});

具体来说,我的目标是footerCallback只对“&#34;忽略&#34;不在条件列中。希望这是明确的,任何帮助表示赞赏。

1 个答案:

答案 0 :(得分:0)

我通过获取reduce函数中求和值的当前索引来解决此问题,然后使用索引访问条件单元格中的相应值。下面是新的jQuery代码:

$("#table1").DataTable({
  "paging": false,
  "searching": false,
  "info": false,    
    "footerCallback": function ( row, data, start, end, display ) {


  var columns = [2, 3];
  //console.log(data);
  var api = this.api();

  // Get sumCondition and put in array     

  _.each(columns, function(idx) {

      var total = api
          .column(idx)
          .data()
          .reduce(function (a, b) {
                // Find index of current value for accessing sumCondition value in same row
                var cur_index = api.column(idx).data().indexOf(b);
                if (api.column(1).data()[cur_index] != "Ignore") {
                return parseInt(a) + parseInt(b);
              }
              else { return parseInt(a); }
          }, 0)         

            $('tr:eq(0) th:eq('+idx+')', api.table().footer()).html(total);
  })

} });

工作小提琴: https://jsfiddle.net/rantoun/552y9j90/14/