代码之家  ›  专栏  ›  技术社区  ›  Joe

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

  •  4
  • Joe  · 技术社区  · 8 年前

    如何 hide / show

    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)
    
    2 回复  |  直到 8 年前
        1
  •  4
  •   Gregor de Cillia    8 年前

    您可以编写一个函数来执行这两个操作,并对每个要隐藏/显示的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)
    

    您还可以更进一步,根据 output_name lapply 而不是 for 然而,由于后者可能会遇到延迟评估的问题。

    toggleViews <- function(input, output_names){
      lapply(output_names, function(output_name){
        toggleView(input, output_name)
      })
    }
    
    ...
    
    toggleViews(input, c("table1", "table2"))
    
        2
  •  1
  •   Jan    3 年前

    shinyjs 使用一次隐藏/显示所有内容 jQuery selectors selector = "[id^='table']" 显示/隐藏 div

    jQuery选择器是灵活的,可能还有其他方法来实现这一点。查看文档。

    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(selector = "[id^='table']")})
      observeEvent(input$show, {show(selector = "[id^='table']")})
    }
    
    shinyApp(ui, server)
    
    推荐文章