此問題基于具有重復單元格編號的 footerCallback
我實施了@andrewJames 的解決方案(謝謝)。
我正在嘗試將表格的最后一列相加,除了薪水System Architect和Senior Javascript Developer
但是現在我使用 JSON 資料時出現了問題。sum總是...而0不是 9 美元
HTML:
<div class="row">
<div class="large-12 columns">
<table id="example" class="display nowrap table1" cellspacing="0" width="100%">
<thead>
<tr>
<th>Seq.</th>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th>Seq.</th>
<th>Name</th>
<th>Position</th>
<th>Salary</th>
</tr>
</tfoot>
</table>
</div>
</div>
jQuery:
var salaryTable = {
"data": [
{
"Seq": "1",
"Name": "Tiger Nixon",
"Position": "System Architect",
"Salary": "$1"
},
{
"Seq": "1",
"Name": "Garrett Winters",
"Position": "Accountant",
"Salary": "$1"
},
{
"Seq": "3",
"Name": "Ashton Cox",
"Position": "Junior Technical Author",
"Salary": "$3"
},
{
"Seq": "4",
"Name": "Cedric Kelly",
"Position": "Senior Javascript Developer",
"Salary": "$4"
},
{
"Seq": "5",
"Name": "Airi Satou",
"Position": "Accountant",
"Salary": "$5"
}
]
};
$(document).ready(function() {
var table = $('#example').DataTable( {
rowReorder: {
selector: 'td:nth-child(2)'
},
data: salaryTable.data,
columns: [
{ data: "Seq" },
{ data: "Name" },
{ data: "Position" },
{ data: "Salary" }
],
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;
};
filteredTotal = api.rows().data().reduce(function (a, b) {
// filterMe will be true or false:
filterMe = b[2] === "System Architect" || b[2] === "Senior Javascript Developer";
// if filterMe is true then use 0, otherwise use the actual amount from b[3]:
salary = filterMe ? 0 : intVal(b[3]);
return a salary;
}, 0 );
// Total over this page
pageTotal = api
.column( 3, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(a) intVal(b);
}, 0 );
// Update footer
$( api.column( 3 ).footer() ).html(
'$' filteredTotal '/ all $' pageTotal
);
},
buttons: ['pdf', 'print']
} );
table.buttons().container()
.appendTo( '#example_wrapper .small-6.columns:eq(0)' );
} );
$(document).foundation();
擺弄問題:https ://jsfiddle.net/87360vyx/1/
uj5u.com熱心網友回復:
這種 Ajax 方法與您之前的 HTML 方法之間的區別在于:
當 DataTables 直接從 HTML 表中提取資料時,一行資料將作為 JavaScript 值陣列處理:
[ '1', 'Tiger Nixon', 'System Architect', ... ]
但是對于您在這個問題中使用的 JSON,等效的資料行作為 JavaScript 物件存盤在 DataTables 中:
{ Seq: "1", Name: "Tiger Nixon", Position: "System Architect", ... }
因此,您不能使用類似的代碼訪問行值b[2]。相反,您必須使用b.Position. 而不是b[3]你必須使用b.Salary.
console.log( b );您可以通過在代碼中為每個不同版本的代碼添加陳述句來親自查看差異rows().data().reduce(...)。這將準確地向您展示 DataTables 如何在內部處理其行資料。
您也可以在這里提供一個官方示例:Ajax 資料源(物件)
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/485387.html
下一篇:使用選擇器從陣列更改時多選
