首页 > 解决方案 > 在 Shiny 中如何用 JavaScript 改变 UI 元素的属性?

问题描述

我知道有一个称为 renderUI 的服务器端方法,但在某些情况下它会导致更新 UI 非常慢,所以我现在依赖于 JavaScript。

我的问题是跟随。我想从 shinymaterial 包中更新 material_card 的标题属性。每次我从单独的下拉菜单中选择一个替代项时,我都希望看到更改的标题。

到目前为止,我的 UI 组件列表包含 tags$script() 对象,它应该观察 selectInput 中的变化(带有 id “dropdown”)。

我的代码如下所示:

library(shinymaterial)
library(shiny)

ui <- material_page(

    titlePanel("Soon to be working JavaScript example!"),

    sidebarLayout(
        sidebarPanel(
            selectInput(
                "dropdown",
                "Dropdown menu",
                c('Hat','Shoes','Jacket')),
                tags$script('
              $(document).on("shiny:inputchanged", function(event) {
                if (event.name === "dropdown") {
                    if(input.dropdown === "Jacket") {
                  //Even this alert is not working, possibly because input.name is not recognized. :(
                  alert("You chose Jacket, now the material card title will be changed to: Jacket selected");
                  //What am I supposed to put here to update the material_card title?
                    } else {
                  //...and here as well...
                }
              });'
            ),
            material_card(
                depth=5,
                title = 'This value needs to be changed according what was chosen in the dropdown menu!')
        ),
        mainPanel(
           h5('Nothing here!')
        )
    )
)

server <- function(input, output) {

    #The server is empty, as it should. :)
}

shinyApp(ui = ui, server = server)

我设法让警报在没有 if(input.dropdown === "Jacket") 验证的情况下工作,但这个验证不起作用:很可能 input.dropdown 甚至无法识别,尽管它与条件面板很好地工作。

此外,我对逻辑更加迷茫:在观察到 selectInput (dropdown) 值的变化之后,我应该如何实际使用 JavaScript 来更新 material_card 标题?

标签: javascriptrshiny

解决方案


library(shinymaterial)
library(shiny)

ui <- material_page(
  
  titlePanel("Soon to be working JavaScript example!"),
  
  sidebarLayout(
    sidebarPanel(
      selectInput(
        "dropdown",
        "Dropdown menu",
        c('Hat','Shoes','Jacket')),
      tags$script(HTML('
              $(document).on("shiny:inputchanged", function(event) {
                if (event.name === "dropdown") {
                  if(event.value === "Jacket") {
                    alert("You chose Jacket, now the material card title will be changed to: Jacket selected");
                    $("#mycard>span.card-title").html("Here is the new card title");
                  } else {
                  //...and here as well...
                  }
                }
              });')
      ),
      material_card(
        depth=5,
        title = 'This value needs to be changed according what was chosen in the dropdown menu!',
        id = "mycard"
      )
    ),
    mainPanel(
      h5('Nothing here!')
    )
  )
)

shinyApp(ui, server = function(input,output){})

推荐阅读