如何在展开所有子行的情况下启动 DT 数据表?

How to start DT datatable with all child rows expanded?

在这个带有子行的 DT example 中,如何展开所有子行的 table?

library(DT)
datatable(
  cbind(' ' = '⊕', mtcars), escape = -2,
  options = list(
    columnDefs = list(
      list(visible = FALSE, targets = c(0, 2, 3)),
      list(orderable = FALSE, className = 'details-control', targets = 1)
    )
  ),
  callback = JS("
  table.column(1).nodes().to$().css({cursor: 'pointer'});
  var format = function(d) {
    return '<div style=\"background-color:#eee; padding: .5em;\"> Model: ' +
            d[0] + ', mpg: ' + d[2] + ', cyl: ' + d[3] + '</div>';
  };
  table.on('click', 'td.details-control', function() {
    var td = $(this), row = table.row(td.closest('tr'));
    if (row.child.isShown()) {
      row.child.hide();
      td.html('&oplus;');
    } else {
      row.child(format(row.data())).show();
      td.html('&CircleMinus;');
    }
  });"
))

PS:Whosebug 迫使我在问题中包含更多细节,但没有其他要添加的...

您还可以使用现有的回调来遍历 table 中的每一行。在该迭代中,您可以创建并打开每个子记录:

table.rows().every( function () { 
  this.child( format(this.data()) ).show(); 
} );

此代码段需要附加到 callback = JS(...) 选项的末尾,如下所示:

  callback = JS(
    "
  table.column(1).nodes().to$().css({cursor: 'pointer'});
  var format = function(d) {
    return '<div style=\"background-color:#eee; padding: .5em;\"> Model: ' +
            d[0] + ', mpg: ' + d[2] + ', cyl: ' + d[3] + '</div>';
  };
  table.on('click', 'td.details-control', function() {
    var td = $(this), row = table.row(td.closest('tr'));
    if (row.child.isShown()) {
      row.child.hide();
      td.html('&oplus;');
    } else {
      row.child(format(row.data())).show();
      td.html('&CircleMinus;');
    }
  });
  table.rows().every( function () { 
    this.child( format(this.data()) ).show(); 
  } );"
  )

结果: