У меня есть две задачи в DataTables:
- To display green row if 'amount' field value is less than 500 and red if amount is more than 5000
- To display sum by 'amount' column at the bottom
Я получаю вывод, если я вызываю каждую функцию по отдельности, но если я пытаюсь вызвать их вместе, я не получаю результата.
var table=$('table.display').DataTable(
{"fnRowCallback": function( nRow, aData, iDisplayIndex,
iDisplayIndexFull )
{
if (aData[5]<500){
$('td', nRow).css('background-color', 'Orange');}
else if (aData[5]>5000){$('td', nRow).css('background-color', '#9EF395');}}
"footerCallback": function ( row, data, start, end, display ) {
var api = this.api(), data;
var intVal = function ( i ) {
return typeof i === 'string' ?
i.replace(/[\$,]/g, '')*1 :
typeof i === 'number' ?
i : 0;};
total = api
.column(2)
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
pageTotal = api
.column( 2, { page: 'current'} )
.data()
.reduce( function (a, b) {
return intVal(a) + intVal(b);
}, 0 );
$( api.column( 2 ).footer() ).html(''+pageTotal +' ( '+
total +' total)');}});} );



![Безумие обратных вызовов в javascript [JS]](https://i.imgur.com/WsjO6zJb.png)


Ну вот:
//source data
var myData = [
{item: 'apple', amount: 250},
{item: 'pear', amount: 570},
{item: 'pinaple', amount: 6700},
{item: 'banana', amount: 140}
];
//data table initialization
var dataTable = $('#mytable').DataTable({
sDom: 't',
data: myData,
columns: [
{data: 'item', title: 'item'},
{data: 'amount', title: 'amount'}
]
});
//append sum
$('#mytable').append(`<tfoot>${Array(dataTable.columns().count()).fill('<th></th>').join('')}</tfoot>`);
var sum = dataTable.column(1).data().reduce((acc, entry) => acc+=entry);
$('#mytable tfoot th').eq(1).text(sum);
//conditional formatting
dataTable.rows().every(function(){
let color = this.data().amount > 5000 ? 'red' : this.data().amount < 500 ? 'green' : 'unset';
$(this.node()).css('background-color', color);
});<!doctype html>
<html>
<head>
<script src = "https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script 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>Сделайте этот пример:
const Table = $('#foo').DataTable({
. . . . . .,
. . . . . .,
drawCallback: function(){
Table.columns(5, {
page: 'current'
}).every(function() {
var sum = this
.data()
.reduce(function(a, b) {
var x = parseFloat(a) || 0;
var y = parseFloat(b) || 0;
return x + y;
}, 0);
console.info(sum);
$(this.footer()).html(sum);
});
}
});
в данном случае столбец был столбцом номер 5