jQuery tablesorter仅为子行分组小计

时间:2016-12-20 19:33:58

标签: jquery jquery-plugins tablesorter

enter image description here我需要将组小计显示在表格的组标题行中。除了数学,一切都很好。在每个组中,我有扩展的父行,其中包含该父项的所有子行的总和。当我总计我的小组时,它会添加所有父母和小组。孩子排在一起,给我的总数是我要找的数字的2倍。有没有办法只添加子行,或只添加父行?这是我到目前为止所做的:

group_callback: function($cell, $rows, column, table) {
   if (column === column) {
      var t, successesTotal = 0;
      $rows.each(function() {
            successesTotal += parseInt($(this).parent('td').eq(successesColumn).text());
});

我尝试过几种看似合乎逻辑的方法,但似乎没有一种方法可行。

successesTotal += parseInt($(this).find('tbody tr.tablesorter-childRow td').eq(successesColumn).text());

没用。也没有:

$rows.each(function() {
     if ($('tr').hasClass('tablesorter-childRow')) {
         successesTotal += parseInt($(this).parent('td').eq(successesColumn).text());
 });

我接近完全按照我的需要完成这项工作,但我仍然需要从计算中排除父行。这将是完美的。在附加的图像中,粗体线是显示其子行总数的父行。成功应该是165&总行应该是6(或2,无论哪种方式都适合我!)我已经花了将近2整天现在试图解决这个问题。任何建议,将不胜感激!!

根据要求,这里是HTML表格(为简化而修改):

<table class="tablesorter">
   <thead>
     <th class="group-word">Column1</th>
     <th class="group-false filter-parsed">Column2</th>
     <th class="group-false filter-parsed">Column3</th>
   </thead>
   <tbody>
      <tr>
         <td>Category1</td>
         <td><a href="#" class="toggle">Category2</a></td>
         <td>Subtotal1</td>
      </tr>
      <tr class="tablesorter-childRow">
         <td>ChildData1</td>
         <td>ChildData2</td>
         <td>ChildData3</td>
      </tr>
      <tr class="tablesorter-childRow">
         <td>ChildData1</td>
         <td>ChildData2</td>
         <td>ChildData3</td>
      </tr>
  </tbody>

我想用ChildData3添加ChildData3。我需要排除SubTotal1。

2 个答案:

答案 0 :(得分:1)

$rows中的group_callback参数同时提供了父行和所有子行,因此您需要过滤掉其中一行。

// only target child rows
$rows.filter('.tablesorter-childRow')

以下是this demo

的代码
var successesColumn = 0;
$("#table").tablesorter({
  theme: "blue",
  widgets: ["group", "filter", "zebra"],
  widgetOptions: {
   group_collapsible : true,
    group_callback: function($cell, $rows, column, table) {
      if (column === successesColumn) {
        var t, successesTotal = 0;
        $rows.filter('.tablesorter-childRow').each(function() {
          successesTotal += parseInt($(this).find('td').eq(successesColumn).text(), 10);
        });
        $cell.find(".group-count").append("; Successes: " + successesTotal );
      }
    }
  }
});

其他修正:

  • $rows变量中包含tr个,因此请使用.find('td')代替父级。
  • 使用10作为十进制整数(ref
  • 时,习惯添加parseInt的基数是一个好习惯

答案 1 :(得分:0)

您可以尝试循环遍历像这样的子行

,而不是循环遍历表中的每一行

$('.tablesorter-childRow').each(function() {});

修改

Check out this JSFiddle