Explanation of fnFooterCallback for DataTables

2019-09-01 20:08发布

问题:

I am creating a table by using the aaData array that is being loaded by a call to a Neo4j Database. I would like to make a footer row that sums up data in the other rows and I found the fnFooterCallback but I don't understand how they used it. This is the example I found on the DataTables website

$(document).ready( function() { 
    $('#example').dataTable( {
        "fnFooterCallback": function( nFoot, aData, iStart, iEnd, aiDisplay ) {
            nFoot.getElementsByTagName('th')[0].innerHTML = "Starting index is "+iStart;
        }
    } );
} )

I know i put the aaData array where is says aData, but I have no clue where the other four parameters come from. I'm new to datatables and can't find anything in the documentation to explain it other than a stands for array, n for node, and i for integer.

My table is nothing novel. The first column is text explaining what's in the row and the remaining columns contain integers. I simply want a footer that says total in the first column and then displays the sums for all the other columns

回答1:

It works this way:

When it draw the table, when it is drawing the footer, it will execute the function you defined. In your example, it just replace the first cell of the footer with the text supplied.

Here is another example I made:

function( nRow, aaData, iStart, iEnd, aiDisplay ) {
        /* Calculate sums of page shown */
        var iPageMargem = 0;
        var iPageClient = 0;
        var iPageMaximo = aaData[ aiDisplay[iStart] ][5]*1;
        var i;
        for ( i=iStart ; i<iEnd ; i++ ) {
            iPageMargem += aaData[ aiDisplay[i] ][2]*1;
            iPageClient += aaData[ aiDisplay[i] ][3]*1;
            if (aaData[ aiDisplay[i] ][5]*1 > iPageMaximo) {
                iPageMaximo = aaData[ aiDisplay[i] ][5]*1;
            };
        }                       
        var nCells = nRow.getElementsByTagName('td');
        nCells[2].innerHTML = $.jqplot.sprintf("%'.2f",iPageMargem);
        nCells[3].innerHTML = $.jqplot.sprintf("%'.0f",iPageClient);
        nCells[4].innerHTML = $.jqplot.sprintf("%'.2f",iPageMargem/iPageClient);
        nCells[5].innerHTML = $.jqplot.sprintf("%'.2f",iPageMaximo);
        iPageMargem=null;
        iPageClient=null;
        iPageMaximo=null;
        i=null;
        nCells=null;
    };

The data is like this:

["Tipo","Segmento","Margem","Clientes","Média","Máximo"],
["PF","Exclusivo",137066708.81,263220,520.73,119718.04],
["RR","Representante Governos",5776837.90,30257,190.93,35185.36],
["PJ","Investidores Institucionais Privados",280488.03,40,7012.20,236619.62],
["","Total","","","",""]

It will calculate the sum of the third and fourth column and the maximum of fifth column, but only of the current page shown. Then It will replace the footer with these values.