initComplete 对数据表的修改未在应用程序初始化时呈现

initComplete modification to datatable not rendering on app initialization

我有一个闪亮的应用程序,它呈现两个数据 table,每个数据都应该有不同的颜色 header。我知道如何在 DT::datatable(options).

initComplete 参数中使用自定义 java 脚本更改个人 table 的 header 的颜色

但是,由于某些原因,当我第一次 运行 在新的 RStudio session 中应用程序时,只有 table 的 header 颜色发生了变化。如下图所示,当我点击刷新时,颜色会正确改变,如果应用程序关闭然后 re-run,它会正确呈现,但这种行为总是在新 [=27= 中首次执行时发生] 我想避免。

有没有办法更改 java 代码来避免这种情况发生?

library(shiny)
library(DT)

ui <- fluidPage(
  dataTableOutput("tbl1"),
  dataTableOutput("tbl2")
)

server <- function(input, output, session) {
  output$tbl1 <- renderDataTable(mtcars %>%
                                   head(n = 5) %>%
                                   datatable(options(
                                     initComplete = JS("function(settings, json) {",
                                                       "$(this.api().table().header()).css({'background-color': 'green'});",
                                                       "}"))))
  output$tbl2 <- renderDataTable(mtcars %>%
                                   head(n = 5) %>%
                                   datatable(options(
                                     initComplete = JS("function(settings, json) {",
                                                       "$(this.api().table().header()).css({'background-color': 'red'});",
                                                       "}"))))
}

shinyApp(ui, server)

这个怎么样

library(shiny)
library(DT)

ui <- fluidPage(
    dataTableOutput("tbl1"),
    dataTableOutput("tbl2"),
    tags$script(
        "
        $('#tbl1').on('preInit.dt', function () {
            $(this).find('thead').css({'background-color': 'green'});
        });
        $('#tbl2').on('preInit.dt', function () {
            $(this).find('thead').css({'background-color': 'red'});
        });
        "
    )
)

server <- function(input, output, session) {
    output$tbl1 <- renderDataTable(mtcars %>%
                                       head(n = 5) %>%
                                       datatable())
    output$tbl2 <- renderDataTable(mtcars %>%
                                       head(n = 5) %>%
                                       datatable())
}

shinyApp(ui, server)

更新

如果您想一次应用所有具有相同颜色的表格,请使用此

    tags$script(
        "
        $('.datatables.html-widget').on('preInit.dt', function () {
            $(this).find('thead').css({'background-color': 'green'});
        });
        "
    )

在定义所有表之后添加此标签,必须在之后而不是之前。