2017-02-21 31 views
0

我試圖用我現有的代碼,它適用於單列總和以獲得總和顯示在兩列 - 我試圖把他們在一個數組中,但它不工作。這是不可能使用簡單的數組解決方案嗎?datatables「footerCallback」函數不顯示結果在頁腳中的兩列(僅在一個)

這是https://jsfiddle.net/setbon/3mvmhL1v/

這是JS:

$(document).ready(function() { 
var table = $('#example').DataTable({ 
    rowReorder: { 
    selector: 'td:nth-child(2)' 
    }, 
    responsive: true, 
    scrollX: true, 
    scrollY: "80vh", 
    scrollCollapse: true, 
     paging: true, 
    lengthChange: false, 
    lengthMenu: [ [10, 25, -1], [10, 25, "All"] ], 
    "order": [[ 0, "asc" ]], 
    "footerCallback": function (row, data, start, end, display) { 
     var api = this.api(), data; 

     // Remove the formatting to get integer data for summation 
     var intVal = function (i) { 
      return typeof i === 'string' ? 
       i.replace(/[\$,]/g, '')*1 : 
       typeof i === 'number' ? 
        i : 0; 
     }; 

     // Total over all pages 
     total = api 
      .column([3,4]) 
      .data() 
      .reduce(function (a, b) { 
       return intVal(a) + intVal(b); 
      }, 0); 

     // Total over this page 
     pageTotal = api 
      .column([3,4], { page: 'current'}) 
      .data() 
      .reduce(function (a, b) { 
       return intVal(a) + intVal(b); 
      }, 0); 

     // Update footer 
     $(api.column([3,4]).footer()).html(
      total 
     ); 
    }, 
    buttons: ['pdf'] 
}); 

table.buttons().container() 
    .appendTo('#example_wrapper .small-6.columns:eq(0)'); 

}); $(document).foundation();

因爲我想總結多個列我現在需要使用額外的插件每https://datatables.net/plug-ins/api/sum()?即使對於該插件,我也找不到一個包含多個專欄的示例,我可以複製並輕鬆進行自定義。

In this SO question該代碼與我所擁有的非常不同,並使我困惑。此外this SO answer is difficult for me to understand and I don't know how to apply to resolve my problem

回答

1

工作例如:https://jsfiddle.net/guanzo/wx5mr9vs/1/

如果我理解正確的話,要在2列同總和。這很容易實現,你不需要插件。

首先,您的行中有一行,編號爲8,具有「東京」而不是薪水編號。這就是爲什麼你的jsfiddle中有$ NaN。

其次,api.column()用於選擇單個列。要選擇多列,只需將函數調用複數,api.columns([3,4]),它應該工作。在你提供的jsfiddle,你只有4列,這意味着你沒有第4列的索引,所以我也

$(api.columns([2,3]).footer()).html(
    '$'+total 
); 

的文檔組織得很好:https://datatables.net/reference/api/

編輯:每一列頁腳包含它的自己和

https://jsfiddle.net/3mvmhL1v/4/

基本上你需要對每列分別進行求和操作。 將兩列的總和合併爲一個變量不會對您有所幫助。

var sumColumns = [3,4] 

sumColumns.forEach(function(colIndex){ 
     // Total over all pages 
    var total = api 
     .column(colIndex) 
     .data() 
     .reduce(function (a, b) { 
      return intVal(a) + intVal(b); 
     }, 0); 

    // Update footer 
    $(api.columns(colIndex).footer()).html(
     total 
    ); 
}) 
+0

Eric,對不起,由於某種原因小提琴沒有保存我所做的更新版本。查看新保存的內容:https://jsfiddle.net/setbon/3mvmhL1v/您應該只看到3行,並且總和應該是兩個單獨的總和 - 兩列中不一樣。我把函數調用成了一個複數,但現在我到處都是零。你能再看一次嗎? –

+0

檢查我編輯的答案。 –

+0

現在好,謝謝!只是好奇你爲什麼要把第一部分移動到上面:「$(document).ready(function(){」?不能將格式設置爲求和的整數數據部分放在$ (document).ready(function(){「用於動作工作? –

相關問題