我有一个带有分页、过滤和 ColVis 插件(列可见性)的 DataTable。通过按一个按钮,我需要获取所有页面的可见和过滤数据,并使用这些数据在下面生成一个新的常规表(这个没有数据表、寻呼机......)。
我尝试oTable.rows({search:'applied'}).data()
获取行,但它不仅获取可见列的数据,还获取隐藏列的数据。无论如何我不知道如何生成新表。
我怎么能这样做?
提前致谢
我有一个带有分页、过滤和 ColVis 插件(列可见性)的 DataTable。通过按一个按钮,我需要获取所有页面的可见和过滤数据,并使用这些数据在下面生成一个新的常规表(这个没有数据表、寻呼机......)。
我尝试oTable.rows({search:'applied'}).data()
获取行,但它不仅获取可见列的数据,还获取隐藏列的数据。无论如何我不知道如何生成新表。
我怎么能这样做?
提前致谢
我的回答基于@davidkonrad 的回答并做了一些修改:
$('button.print-bt').on('click', function() {
var fvData = oTable.rows({ search:'applied', page: 'all' }).data();
$('#main_wrapper').append(
'<table id="newTable">' +
'<thead>'+
'<tr>'+
$.map(oTable.columns().visible(),
function(colvisible, colindex){
return (colvisible) ? "<th>" + $(oTable.column(colindex).header()).html() + "</th>" : null;
}).join("") +
'</tr>'+
'</thead>'+
'<tbody>' +
$.map(fvData, function(rowdata, rowindex){
return "<tr>" + $.map(oTable.columns().visible(),
function(colvisible, colindex){
return (colvisible) ? "<td>" + $('<div/>').text(rowdata[colindex]).html() + "</td>" : null;
}).join("") + "</tr>";
}).join("") +
'</tbody></table>'
);
});
我的答案可能不适用于将对象作为数据源的表,并且可能需要在使用rowdata[colindex]
.
我正在使用$('<div/>').text(data).html()
技巧来编码可能存在于数据中的 HTML 实体。
请参阅此 JSFiddle进行演示。
oTable.rows({ search:'applied', visible:true }).data();
无效。请参阅rows()
选择器修饰符的文档。
为了获得过滤后的可视行,您应该使用page: 'current'
,所以
var fvData = oTable.rows({ search:'applied', page: 'current' }).data();
......会做的伎俩。要从头开始创建一个全新的表,并插入上面过滤的可见行,您可以将其添加到您的点击处理程序中:
$('#main_wrapper').append('<table id="newTable">'+
'<thead>'+
'<tr>'+
'<th>Column 1</th>'+
'<th>Column 2</th>'+
'<th>Column 3</th>'+
'<th>Column 4 (hidden)</th>'+
'</tr>'+
'</thead>'+
'<tbody></tbody></table>');
var newTable = $("#newTable").DataTable();
for (var i=0;i<fvData.length;i++) {
newTable.row.add(fvData[i]).draw();
}
分叉的小提琴-> https://jsfiddle.net/sdz1n1gk/