Datatables: custom function inside of fnRowCallbac

2019-07-09 20:28发布

问题:

Trying to run function inside of fnRowCallback. jQuery reports this error:

too much recursion
/js/jquery.js
Line: 4

Cannot find this neverending loop. alert(aData.toSource()); shows array which i'm trying to loop through.

    var clientId = 1234;
    var reportData = $('#report-data').dataTable({
        "bProcessing": true,
        "bServerSide": true,
        "sAjaxSource": "?go=report&do=process&action=get-report",
        "fnServerData": function ( sSource, aoData, fnCallback ) {
            aoData.push({ "name": "client_id", "value": clientId });
            $.getJSON( sSource, aoData, function (json) { 
                fnCallback(json);
            });
        },
        "fnRowCallback": function (nRow, aData, iDisplayIndex, iDisplayIndexFull) {
            formatDates(nRow,aData);
        },
    });

    function formatDates(nRow,aData) {
//      alert(aData.toSource());
        for(i=0; i!=aData.length; i++) {
            if (aData[i].match(/^([0-9]{4}-[0-9]{2}-[0-9]{2})T([0-9]{2}:[0-9]{2}):[0-9]{2}\.[0-9]{3}$/gi)) {
                reportData.fnUpdate('New Date Format', nRow['_DT_RowIndex'], i);
            }
        }
    }

回答1:

For each row, fnRowCallback is called, which calls fomatDates, which is calling fnUpdate, which redraws the table, calling fnRowCallback...

EDIT: Thinking about this more, forcing a redraw may cause the recursion problem all over again. Instead, replace the call to fnUpdate in your fnRowCallback to this:

$(nRow).find('td:eq(' + i + ')').text('New Date Format');

This will update the text of the i-th TD element to 'New Date Format', which is what it appears you're wanting to do.