Javascript 在数据表中添加字段的总和
这个问题以前有人问过,但作为JavaScript的绝对初学者,我不知道如何将其应用到我的代码中。我希望“G”字段的总和和“AB”字段的总和都显示在表的页脚中 这是我的密码Javascript 在数据表中添加字段的总和,javascript,jquery,datatables,Javascript,Jquery,Datatables,这个问题以前有人问过,但作为JavaScript的绝对初学者,我不知道如何将其应用到我的代码中。我希望“G”字段的总和和“AB”字段的总和都显示在表的页脚中 这是我的密码 <div align="center"> <table id = 'battingtbl' class="display compact nowrap"> <thead> <tr> <th>
<div align="center">
<table id = 'battingtbl' class="display compact nowrap">
<thead>
<tr>
<th>YEAR</th>
<th>AGE</th>
<th>G</th>
<th>AB</th>
</tr>
</thead>
<tbody>
{% for stat in playerdata.masterbatting_set.all %}
<tr>
<td>{{ stat.year }}</td>
<td>{{ stat.age }}</td>
<td>{{ stat.g }}</td>
<td>{{ stat.ab }}</td>
</tr>
{% endfor %}
</tbody>
</table>
<script>
$(document).ready(function () {
$('#battingtbl').DataTable({
"searching": true,
"pageLength": 40,
"scrollX": true,
"paging": false,
"info": false,
})
});
</script>
年
年龄
G
AB
{playerdata.masterbatting_set.all%中的状态为%
{{stat.year}
{{stat.age}}
{{stat.g}}
{{stat.ab}}
{%endfor%}
$(文档).ready(函数(){
$('\35; BATTINGBL').DataTable({
“搜索”:没错,
“页面长度”:40,
“scrollX”:正确,
“分页”:false,
“信息”:错误,
})
});
我通常不建议用HTML源代码填充DataTable,我发现这种方法既单调又缓慢
然而,假设您希望在每次重新绘制时重新计算这些总计(表过滤),我建议使用选项填充您的总计:
drawCallback: () => {
// grab DataTables insurance into the variable
const table = $('#battingtbl').DataTable();
// extract all the data for all visible columns
const tableData = table.rows({search:'applied'}).data().toArray();
// summarize row data for columns 3,4 (indexes 2, 3)
const totals = tableData.reduce((total, rowData) => {
total[0] += parseFloat(rowData[2]);
total[1] += parseFloat(rowData[3]);
return total;
// starting point for reduce() totals for 2 columns equal to zero each
}, [0,0]);
// populate footer cells for columns 3, 4 (indexes 2, 3) with corresponding array total
$(table.column(2).footer()).text(totals[0]);
$(table.column(3).footer()).text(totals[1]);
}
上面要求您将
部分附加到服务器端准备的静态HTML部分:
<tfoot>
<tr>
<th colspan="2">Totals:</th>
<th></th>
<th></th>
</tr>
</tfoot>
总数:
所以,完整的示例可能看起来像这样:
年
年龄
G
AB
2016
24
15
6.
2018
32
5.
7.
2016
28
14
9
2015
25
9
7.
总数:
$(文档).ready(函数(){
$('#BattingBL')。数据表({
“搜索”:没错,
“页面长度”:40,
“scrollX”:正确,
“分页”:false,
“信息”:错误,
drawCallback:()=>{
常量表=$('#battingbl')。数据表();
const tableData=table.rows({
搜索:“已应用”
}).data().toArray();
const totals=tableData.reduce((总计,行数据)=>{
总计[0]+=parseFloat(行数据[2]);
总计[1]+=parseFloat(行数据[3]);
返回总数;
}, [0, 0]);
$(table.column(2.footer()).text(总计[0]);
$(table.column(3).footer()).text(总计[1]);
}
})
});
好的,我会处理一下。如果我找不到,我会和你联系。谢谢你的帮助,汉克!我感谢您的帮助(这很有用),但我认为这对我用来提取数据的for循环不起作用。如果我在这个问题上错了,请纠正我。这似乎对meSorry不起作用,我花了一段时间才做出回应。是的,谢谢你,它确实起作用了!我看到你在使用索引。如果我的表有更多的列…我怎么把总数也算成第五列呢?我已经注释了我的代码,这样你就更容易扩展它了。好吧,太棒了!我现在已经完全可以用了。最后一件事。怎么样?我想取一列的平均值?算了吧,这很简单-用总数除以tableData
中的行数,例如$(table.column(2.footer()).text(totals[0]/tableData.length)