【发布时间】:2019-06-04 21:05:48
【问题描述】:
我正在使用 DataTables 来计算列中的所有行并在表的页脚中显示总计。
问题出在这里:似乎每当我正在计算的列的任何行中有空值时,总数都会显示为 NaN。
我怎样才能让 DataTables 忽略列中的空值而只对非空值求和?
<div align="center">
<table id = 'mytabl' class="display compact nowrap">
<thead>
<tr>
<th>Column 1</th>
<th>Column 2</th>
</tr>
</thead>
<tbody>
{% for num in numberdata.mytable_set.all %}
<tr>
<td>{{ num.col1 }}</td>
<td>{{ num.col2 }}</td>
</tr>
{% endfor %}
</tbody>
<tfoot>
<tr>
<th></th>
<th></th>
</tr>
</tfoot>
</table>
<script>
$(document).ready(function() {
$('#mytabl').DataTable({
"searching": true,
"pageLength": 40,
"scrollX": true,
"paging": false,
"info": false,
drawCallback: () => {
const table = $('#mytabl').DataTable();
const tableData = table.rows({
search: 'applied'
}).data().toArray();
const totals = tableData.reduce((total, rowData) => {
total[0] += parseFloat(rowData[1]);
total[1] += parseFloat(rowData[2]);
return total;
}, [0, 0]);
$(table.column(1).footer()).text(totals[0]);
$(table.column(2).footer()).text(totals[1]);
}
})
});
</script>
【问题讨论】:
-
尝试将rowData[1]改为+rowData[1]......
-
这可能是最好/最简单的方法^
标签: javascript jquery datatables