从docs数据表我们看到如何将子行或详细信息添加到数据中的每一行(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都有空的扩展名,在这里我不希望展开按钮显示,只是空白区域。扩展名为非空的另外两个应该仍然有按钮来显示此信息。
答案 0 :(得分:1)
您可以使用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');
}
}
});