我的要求是创建一个表,其父行可单击并具有n级子级。我尝试使用数据表并成功显示第一级别的孩子,但未能显示下一级别。
function format(d) {
// `d` is the original data object for the row
if (d.child.length) {
var tableStr = '<table cellspacing="0" class="display" cellspacing="0" width="100%">';
for (var i = 0; i < d.child.length; i++) {
tableStr += '<tr>' +
'<td class="details-control"></td>' +
'<td>' + d.child[i].name + '</td>' +
'<td>' + d.child[i].position + '</td>' +
'<td>' + d.child[i].office + '</td>' +
'<td>' + d.child[i].salary + '</td>' +
'</tr>';
}
return tableStr + '</table>';
}
}
$(document).ready(function() {
var table = $('#example').DataTable({
"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');
}
});
});
// object.txt中的数据内容
var tableData = {[
{
"name": "Tiger Nixon",
"position": "System Architect",
"salary": "$320,800",
"start_date": "2011/04/25",
"office": "Edinburgh",
"extn": "5421",
"child": [{
"name": "Garrett Winters",
"position": "Accountant",
"salary": "$170,750",
"start_date": "2011/07/25",
"office": "Tokyo",
"extn": "8422",
"child": [{
"name": "Cedric Kelly",
"position": "Senior Javascript Developer",
"salary": "$433,060",
"start_date": "2012/03/29",
"office": "Edinburgh",
"extn": "6224",
"child": []
}]
},{
"name": "Ashton Cox",
"position": "Junior Technical Author",
"salary": "$86,000",
"start_date": "2009/01/12",
"office": "San Francisco",
"extn": "1562",
"child": []
}]
}]};