在同一数据集中具有父子关系的JQuery Datatable。 如何在表中将其显示为父子行?
我有一个嵌套的数据集。 数据集中的少数记录是同一数据集中其他记录的子记录。 父级为null的记录没有任何子元素,但具有与之关联的值的记录将在同一数据集中指示其父级。 如何在具有父子关系的jQuery Datatable中表示这一点。
我刚刚操纵了公共数据集来解释我的要求。 与下面的数据集示例一样,Record with Name – Tiger Nixon有两个子记录,它们在同一数据集中作为单独的记录。
如何实现的一个例子将有很大帮助。
{ "data": [ { "name": "Tiger Nixon", "parent": "null", "position": "System Architect", "salary": "$320,800", "start_date": "2011/04/25", "office": "Edinburgh", "extn": "5421" }, { "name": "Garrett Winters", "parent": "Tiger Nixon", "position": "Accountant", "salary": "$170,750", "start_date": "2011/07/25", "office": "Tokyo", "extn": "8422" }, { "name": "Ashton Cox", "parent": "null", "position": "Junior Technical Author", "salary": "$86,000", "start_date": "2009/01/12", "office": "San Francisco", "extn": "1562" }, { "name": "Cedric Kelly", "parent": "Tiger Nixon", "position": "Senior Javascript Developer", "salary": "$433,060", "start_date": "2012/03/29", "office": "Edinburgh", "extn": "6224" } ] }
解
您可以使用ajax.dataSrc
将原始数据存储在g_dataFull
并过滤并返回仅包含父数据的数据以显示在主表中。
当子行在format()
函数中时,您需要迭代完整数据集g_dataFull
并查找并显示包含子项的行( this.parent === d.name
)。
DEMO
var g_dataFull = []; /* Formatting function for row details - modify as you need */ function format ( d ) { var html = ''; var dataChild = []; var hasChildren = false; $.each(g_dataFull, function(){ if(this.parent === d.name){ html += '' + $('').text(this.name).html() + ' ' + '' + $('').text(this.position).html() + ' ' + '' + $('').text(this.office).html() +' ' + '' + $('').text(this.salary).html() + ' '; hasChildren = true; } }); if(!hasChildren){ html += 'There are no items in this view. '; } html += '
'; return html; } $(document).ready(function() { var table = $('#example').DataTable( { "ajax": { "url": "https://api.myjson.com/bins/3mbye", "dataSrc": function(d){ g_dataFull = d.data; var dataParent = [] $.each(d.data, function(){ if(this.parent === "null"){ dataParent.push(this); } }); return dataParent; } }, "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'); } } ); } );
td.details-control { background: url('http://sofzh.miximages.com/jquery/details_open.png') no-repeat center center; cursor: pointer; } tr.shown td.details-control { background: url('http://sofzh.miximages.com/jquery/details_close.png') no-repeat center center; }
Name Position Office Salary Name Position Office Salary