Make jQuery datatables keep the row number assigne

2019-07-28 19:09发布

问题:

I've got the following code to create a row number in jQuery Datatables:

"fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ 
        var index = iDisplayIndexFull + 1; 
        $('td:eq(0)', nRow).html(index); 
        return nRow;
     },

However, when I search for a certain value, the row numbers update. This is expected. My question is, is there anyway to make the row numbers remain the same after they are initially created?

Example:

 Initial output
 1     Team1
 2     Team2
 3     Team3
 4     Team4
 5     Team5

 After Searching
 2     Team2
 5     Team5

Is this possible?

回答1:

"fnDrawCallback": function ( oSettings ) {
 /* Need to redo the counters if filtered or sorted */
 if ( oSettings.bSorted || oSettings.bFiltered )
 {
 for ( var i=0, iLen=oSettings.aiDisplay.length ; i<iLen ; i++ )
 {
 $('td:eq(0)', oSettings.aoData[ oSettings.aiDisplay[i] ].nTr ).html( i+1 );
 }
 }
 }


回答2:

You could store the original id in aData:

aData.index = iDisplayIndexFull + 1;

And then, you could access it later on with:

var index = oTable.fnGetData(your_row).index;


回答3:

I'd set a data attribute on the rows initially like so:

"fnRowCallback": function(nRow, aData, iDisplayIndex, iDisplayIndexFull){ 
        var index = iDisplayIndexFull + 1; 
        $('td:eq(0)', nRow).attr('data-index',$('td:eq(0)', nRow).attr('data-index')||index);
        $('td:eq(0)', nRow).html($('td:eq(0)', nRow).attr('data-index',index));
        return nRow;
     },