向数据表中的某些条目添加详细信息/子行



从数据表的文档中,我们可以看到如何将子行或详细信息添加到数据(JSON/CSV文件)中的每一行。然而,我不想要一个扩展按钮——扩展名和前两个数据条目一样是空的。这就是我的工作:

Javascript

function format ( d ) {
// `d` is the original data object for the row
return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">'+
'<tr>'+
'<td>Full name:</td>'+
'<td>'+d.name+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extension number:</td>'+
'<td>'+d.extn+'</td>'+
'</tr>'+
'<tr>'+
'<td>Extra info:</td>'+
'<td>And any further details here (images etc)...</td>'+
'</tr>'+
'</table>';
}
$(document).ready(function() {
var table = $('#example').DataTable( {
"ajax": "../ajax/data/objects.txt",
"columns": [
{
"className":      'details-control',
"orderable":      false,
"data":           null,
"defaultContent": ''
},
{ "data": "name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "salary" }
],
"order": [[1, 'asc']]
} );
// Add event listener for opening and closing details
$('#example tbody').on('click', 'td.details-control', function () {
var tr = $(this).closest('tr');
var row = table.row( tr );
if ( row.child.isShown() ) {
// This row is already open - close it
row.child.hide();
tr.removeClass('shown');
}
else {
// Open this row
row.child( format(row.data()) ).show();
tr.addClass('shown');
}
} );
} );

HTML

<table id="example" class="display" cellspacing="0" width="100%">
<thead>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</thead>
<tfoot>
<tr>
<th></th>
<th>Name</th>
<th>Position</th>
<th>Office</th>
<th>Salary</th>
</tr>
</tfoot>
</table>

JSON

{
"data": [
{
"id": "1",
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": ""
},
{
"id": "2",
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": ""
},
{
"id": "3",
"name": "Ashton Cox",
"position": "Junior Technical Author",
"salary": "$86,000",
"start_date": "2009/01/12",
"office": "San Francisco",
"extn": "1562"
},
{
"id": "4",
"name": "Cedric Kelly",
"position": "Senior Javascript Developer",
"salary": "$433,060",
"start_date": "2012/03/29",
"office": "Edinburgh",
"extn": "6224"
},
]

正如你所看到的,条目1和2都有空的扩展名,这里我根本不想显示扩展按钮,只是空白。另外两个扩展名为非空的地方应该仍然有显示此信息的按钮。

您可以使用createdRow()检查详细信息单元格的内容,如果该单元格不为空,则有条件地添加details-control类。

例如,这将检查extn字段是否具有非空值

$(document).ready(function() {
var table = $('#example').DataTable({
"data": data.data,
"columns": [{
"orderable": false,
"data": null,
"defaultContent": ''
}, {
"data": "name"
}, {
"data": "position"
}, {
"data": "office"
}, {
"data": "salary"
}],
"order": [
[1, 'asc']
],
"createdRow": function(row, data, dataIndex) {
if (data.extn !== "") {
$(row).find("td:eq(0)").addClass('details-control');
}
}
});

以下是Fiddle演示:https://jsfiddle.net/zephyr_hex/rhgL0294/20/

最新更新