问题
I am currently using Datatables to display three columns with a varying number of rows of information.
The table is setup so that when a column header is clicked the table is sorted in reference to that column. I am trying to use fnGetData to get the visible data that is now sorted. However, my attempt simply returns the original data the table was initialized with.
This is a roughly what the code looks like:
$("#example").click(function() {
oTable = $('#' + tableName).dataTable();
var secondCellArray=[];
$.each( oTable.fnGetData(), function(i, row){
secondCellArray.push( row[0],row[1],row[2]);
})
console.log( secondCellArray)
});
回答1:
The underscrore (_) method is particularly useful here. It's worked well for me in the past. It will return an array of objects.
oTable._('tr', {"filter":"applied"});
回答2:
The fnGetData
method is the correct (for Datatables version <= 1.10) way to extract data:
http://legacy.datatables.net/api#fnGetData
Per that documentation that function will:
Get the data for the whole table, an individual row or an individual cell based on the provided parameters.
Here's an example from that documentation:
oTable = $('#example').dataTable();
oTable.$('tr').click( function () {
var data = oTable.fnGetData( this );
// ... do something with the array / object of data for the row
});
NOTE: My original answer mentioned using fnGetData
without an argument (which worked for me a long time ago), and the docs suggest that should still work ("the data for the whole table"), but since that answer got down-voted and documentation doesn't specifically provide an example of its usage, I'm going to avoid recommending using it that way.
Of course, the old Datatables is kind of terrible, so most likely (unless you have a lot of code built around the old Datables) your best bet is to upgrade to the newest version (or to another table/grid library entirely).
来源:https://stackoverflow.com/questions/11513858/retrieving-visible-data-from-datatables