JQuery Datatable with parent child relationship in same dataset. How to display it as parent child rows in the table?

后端 未结 1 1058
忘了有多久
忘了有多久 2021-01-06 17:49

I have a nested dataset. Few records in the dataset are child to other records in the same dataset. The records that have parent as null do not have any child elements, but

1条回答
  •  萌比男神i
    2021-01-06 18:21

    SOLUTION

    You can use ajax.dataSrc to store original data in g_dataFull and filter and return data containing parents only to be displayed in the main table.

    When child row is being in format() function you need to iterate full dataset g_dataFull and find and display rows containing children (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 += 
                '' + 
                '' + 
                '' + 
                '';
             
              hasChildren = true;
           }
        });
      
        if(!hasChildren){
            html += '';
         
        }
      
     
        html += '
    ' + $('
    ').text(this.name).html() + '
    ' + $('
    ').text(this.position).html() + '
    ' + $('
    ').text(this.office).html() +'
    ' + $('
    ').text(this.salary).html() + '
    There are no items in this view.
    '; 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('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_open.png') no-repeat center center;
        cursor: pointer;
    }
    tr.shown td.details-control {
        background: url('https://raw.githubusercontent.com/DataTables/DataTables/1.10.7/examples/resources/details_close.png') no-repeat center center;
    }
    
     
    
    
    
    Name Position Office Salary
    Name Position Office Salary

    0 讨论(0)
提交回复
热议问题