我想计算表中“ TR”列的平均值,但无法使用jquery进行计算。
我的jquery代码:
table = $("#beyannameTable").DataTable(
{
dom: 'Bfrtip',
buttons: ['excel', 'print'],
lengthChange: false,
searching: false,
paging: false,
"ajax": {
"url": "/Raporlama/ITH_Operasyon",
"type": "GET",
"datatype": "json",
data: { tescilTrh1: $("#tescilTrh1").val(), tescilTrh2: $("#tescilTrh2").val() },
},
"columns": [
{ "data": "Kullanici" },
{ "data": "Ref" },
{ "data": "Tescil_No" },
{ "data": "UNVAN" },
{ "data": "TescilTarihi" },
{ "data": "GumrukAdi" },
{ "data": "Cekildi_Tarih" },
{ "data": "GumrukEvraklar_Tarih" },
{ "data": "TR" }
]
});
答案 0 :(得分:0)
您可以使用.column().data()
方法访问所需的列数据。如果您需要根据可见行动态地重新计算列平均值,则可以使用选择器修饰符{search: 'applied'}
作为.column()
中的第二个参数,并使用选项drawCallback
来对每个列调用平均值重新计算重新绘制。
请在该方法的演示下方结帐:
//sample source data
const srcData = [
{id: 1, name: 'Steve', age: 24},
{id: 2, name: 'Chris', age: 31},
{id: 3, name: 'Martha', age: 28},
{id: 4, name: 'Sam', age: 33}
];
//DataTables initialization
$('#mytable').DataTable({
dom: 'ft',
data: srcData,
columns: [
{title: 'id', data: 'id'},
{title: 'name', data: 'name'},
{title: 'age', data: 'age'}
],
drawCallback: () => $('#avgage').text(avgAge())
});
//average age calculation
function avgAge() {
let columnData = $('#mytable').DataTable().column(2,{search:'applied'}).data().toArray();
return Math.round(columnData.reduce((sum, item) => sum+=item)/columnData.length);
};
//Append <tfoot>
$('#mytable').append(`<tfoot><tr><td colspan="3">Average age: <span id="avgage">${avgAge()}</span></td></tr></tfoot>`);
<!doctype html>
<html>
<head>
<script type="application/javascript" src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script type="application/javascript" src="https://cdn.datatables.net/1.10.19/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.19/css/jquery.dataTables.min.css">
</head>
<body>
<table id="mytable"></table>
</body>
</html>