R 如何使用shinyjs同时隐藏/显示多个元素?

R 如何使用shinyjs同时隐藏/显示多个元素?,r,shiny,shinyjs,R,Shiny,Shinyjs,如何使用shinyjs同时隐藏/显示多个元素?在下面的示例中,我的目标是用两行代码(而不是四行代码)隐藏/显示两个表。我为什么要这样做?实际上,我正在处理多个表和多个事件,这样一次显示/隐藏它们将使代码更干净 library(shiny) library(shinyjs) ui <- fluidPage( useShinyjs(), actionButton("hide","Hide!"), actionButton("show","Show!"), tableOutpu

如何使用shinyjs同时隐藏/
显示
多个元素?在下面的示例中,我的目标是用两行代码(而不是四行代码)隐藏/显示两个表。我为什么要这样做?实际上,我正在处理多个表和多个事件,这样一次显示/隐藏它们将使代码更干净

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  actionButton("hide","Hide!"),
  actionButton("show","Show!"),
  tableOutput("table1"),
  tableOutput("table2"))

server <- function(input, output, session) {
  output$table1 <- renderTable({head(iris)})
  output$table2 <- renderTable({head(iris)})
  observeEvent(input$hide, {hide("table1")})
  observeEvent(input$show, {show("table1")})
  observeEvent(input$hide, {hide("table2")})
  observeEvent(input$show, {show("table2")})}

shinyApp(ui, server)
库(闪亮)
图书馆(shinyjs)

ui您可以编写一个函数来执行这两个操作,并对每个要隐藏/显示的ui元素调用它们一次

library(shiny)
library(shinyjs)

toggleView <- function(input, output_name){
  observeEvent(input$show, {show(output_name)})
  observeEvent(input$hide, {hide(output_name)})
}

ui <- fluidPage(
  useShinyjs(),
  actionButton("hide","Hide!"),
  actionButton("show","Show!"),
  tableOutput("table1"),
  tableOutput("table2"))

server <- function(input, output, session) {
  output$table1 <- renderTable({head(iris)})
  output$table2 <- renderTable({head(iris)})
  toggleView(input, "table1")
  toggleView(input, "table2")
}

shinyApp(ui, server)

伟大的为什么我们需要
input
作为
toggleView
的参数?我在没有设置的情况下尝试了它,但它不起作用。如果您在服务器内部定义了
toggleView
函数,那么
input
参数应该是不必要的。或者,您也可以使用
input=getDefaultReactiveDomain()$input
server
内部定义
toggleView
有什么问题吗?如果函数/对象定义(1)需要大量时间运行或(2),将函数/对象定义放在服务器外部(在
global.R
中)是有意义的在
ui.R
server.R
中使用。在本例中,这两个条件都不满足。我只是编辑了答案,允许在
output\u name
中输入向量。也许你可以用这种方式保存一些额外的代码行。
toggleViews <- function(input, output_names){
  lapply(output_names, function(output_name){
    toggleView(input, output_name)
  })
}

...

toggleViews(input, c("table1", "table2"))