jquery 单击全部展开时无法向DataTables的子行添加信息

z4bn682m  于 2023-04-20  发布在  jQuery
关注(0)|答案(2)|浏览(113)

我正在尝试将基于父行的数据添加到子行。当我单击“全部展开”时,我希望能够基于父行将数据添加到子行。当我单击该按钮时,所有行都打开,但容器仅添加到第一行,其中包含数据表当前页上最后一行的信息
下面是我的例子:

/* Formatting function for row details - modify as you need */
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': 'https://gyrocode.github.io/files/jquery-datatables/objects.json',
        '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');
        }
    });

    // Handle click on "Expand All" button
    // Handle click on "Expand All" button
    $('#btn-show-all-children').on('click', function(){
        let containers, user_name;
        table.rows().every(function(){
            if(!this.child.isShown()){
              $('#example tbody>tr').each(function() {
                user_name = $(this).find('.sorting_1').text();
                containers = document.createElement('div');
                containers.setAttribute('id', `container_${user_name.replace(' ', '_')}`);
                $(`#container_${user_name.replace(' ', '_')}`).text(user_name);
              });
               this.child(containers).show();
                $(this.node()).addClass('shown');
            }
        });
    });

    // Handle click on "Collapse All" button
    $('#btn-hide-all-children').on('click', function(){
        // Enumerate all rows
        table.rows().every(function(){
            // If row has details expanded
            if(this.child.isShown()){
                // Collapse row details
                this.child.hide();
                $(this.node()).removeClass('shown');
            }
        });
    });
});
td.details-control {
    background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_open.png') no-repeat center center;
    cursor: pointer;
}
tr.shown td.details-control {
    background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_close.png') no-repeat center center;
}
<link rel='stylesheet' type='text/css' href='https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>

<button id="btn-show-all-children" type="button">Expand All</button>
<button id="btn-hide-all-children" type="button">Collapse All</button>
<hr>
<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>

正如你所看到的,当你点击expand all时,每一行都应该有一个容器,其名称在父级中。在下面的截图中,你可以看到Airi Satou的子div的名称为Cedric Kelly。为什么会发生这种情况?

hgc7kmma

hgc7kmma1#

当你在every(..循环中使用.each循环时,它会迭代两次,即:如果every..循环获取第一行,那么.each循环将遍历整个表(行中的每个tr),这就是为什么div中只显示最后一个值。
但是,这里不需要使用each循环,因为您可以通过使用this.data()获取name值,它将返回您的行中的所有数据 JSON Object。因此,只需使用.name获取name value,然后将该值添加到使用.innerHTML生成的div中。

  • 演示代码 *:
/* Formatting function for row details - modify as you need */
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': 'https://gyrocode.github.io/files/jquery-datatables/objects.json',
    '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');
    }
  });

  // Handle click on "Expand All" button
  // Handle click on "Expand All" button
  $('#btn-show-all-children').on('click', function() {
    let containers, user_name;
    var count = 0;
    table.rows().every(function() {
    //get data from row this will return values in json object..
      var d = this.data();
      if (!this.child.isShown()) {
        containers = document.createElement('div');
        containers.setAttribute('id', `container_${d.name.replace(' ', '_')}`);
        containers.innerHTML = d.name;//add value in inside div crated
        this.child(containers).show();
        $(this.node()).addClass('shown'); 
      }
    });
  });

  // Handle click on "Collapse All" button
  $('#btn-hide-all-children').on('click', function() {
    // Enumerate all rows
    table.rows().every(function() {
      // If row has details expanded
      if (this.child.isShown()) {
        // Collapse row details
        this.child.hide();
        $(this.node()).removeClass('shown');
      }
    });
  });
});
td.details-control {
  background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_open.png') no-repeat center center;
  cursor: pointer;
}

tr.shown td.details-control {
  background: url('https://cdn.rawgit.com/DataTables/DataTables/6c7ada53ebc228ea9bc28b1b216e793b1825d188/examples/resources/details_close.png') no-repeat center center;
}
<link rel='stylesheet' type='text/css' href='https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css'>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script>

<button id="btn-show-all-children" type="button">Expand All</button>
<button id="btn-hide-all-children" type="button">Collapse All</button>
<hr>
<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>
kmb7vmvb

kmb7vmvb2#

var isChildRowOpen = false;

$("#example tbody").on("click", "td.details-control", function () {
  var tr = $(this).closest("tr");
  var row = table.row(tr);

  if (isChildRowOpen) {
    // Close the child row if it is already open
    row.child.hide();
    tr.removeClass("shown");
    isChildRowOpen = false;
  } else {
    // Display the child row and set isChildRowOpen to true
    row.child(format(row.data())).show();
    tr.addClass("shown");
    isChildRowOpen = true;
  }
});

// Close the child row if the user clicks the close button within it
$("#example tbody").on("click", ".close-child-row", function() {
  var tr = $(this).closest("tr");
  var parentTr = tr.prev(".parent-row");
  var parentRow = table.row(parentTr);
  
  parentRow.child.hide();
  parentTr.removeClass("shown");
  isChildRowOpen = false;
});

相关问题