You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何让Shiny应用中DT表格初始加载时所有子行默认展开

解决方案

你只需要在原有DT回调的JS代码末尾,新增一段遍历所有行并主动触发展开的逻辑即可,不影响原有点击收起/展开的交互功能。另外原代码中子行格式化函数里的样式属性有笔误,我顺便修正为可用的背景样式,你也可以根据需求自行调整。

核心修改点

在DT::JS()包裹的回调代码最后,添加以下代码:

// 初始加载时自动展开所有子行
table.rows().every(function() {
  const row = this;
  const td = $(row.node()).find('td.details-control');
  row.child(format(row.data())).show();
  td.html('⊖');
});

完整可运行代码

# Load packages
library(shiny)
library(DT)

# Set up dummy data frame.
df = data.frame(
  expand_child_row = "⊕",
  col1 = c(1, 2, 3),
  col2 = c("a", "b", "c"),
  child_row_col = "additional_info"
)

# Define app UI
ui = shiny::fluidPage(
  DT::DTOutput(outputId = "example_table")
)

# Define app server
server = function(input, output) {
  output$example_table = DT::renderDataTable({
    dt = DT::datatable(
      data = df,
      options = list(
        dom = "t",
        columnDefs = list(
          list(visible = FALSE, targets = 3),
          # Define options for child row column
          list(orderable = FALSE, className = 'details-control', targets = 0)
        )
      ),
      rownames = FALSE,
      escape = FALSE,
      callback = DT::JS("
        // Change mouse to pointer when hovering over expand plus sign
        table.column(0).nodes().to$().css({cursor: 'pointer'});
        
        // Function to format the child row text
        var format = function(d) {
          return '<div style=\"background:#f5f5f5; padding: 10px;\"> ' + d[3] + '</div>';
        };
        
        // Function to toggle (show/hide) child row visibility upon click.
        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() {
          const row = this;
          const td = $(row.node()).find('td.details-control');
          row.child(format(row.data())).show();
          td.html('&CircleMinus;');
        });
      ")
    )
    return(dt)
  })
}

shiny::shinyApp(ui = ui, server = server)

运行上述代码后,表格首次加载就会自动展开所有子行,完全符合需求效果。

内容的提问来源于stack exchange,提问作者ForceLeft415

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 05:54:05