【问题标题】:Server Code working with Javascript in Shiny在 Shiny 中使用 Javascript 的服务器代码
【发布时间】:2021-07-12 16:55:52
【问题描述】:

我想了解我们如何与纯 JS(或 Jquery)交互代码的服务器部分。我准备了两个示例-基本上我想在用户单击按钮时隐藏 h4( )。第一个示例按预期工作,但第二个示例不起作用,因为 h4() 在服务器的 renderUI() 中。我知道这可以通过 observeEvent 或 shinyJS 包解决,但我更感兴趣的是让它与纯 JS 一起工作,而不是在服务器中运行 JS 代码。

示例 1

library(shiny)

ui <- fluidPage(
  fluidRow(
    h4("Testing"),
    actionButton("Disable", "Disable Element"),
    tags$script("
    $(document).ready(function() {
      $('#Disable').click(function(){
      $('h4').css('display', 'none');
      });
})")
  )
)

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

示例 2

ui <- fluidPage(
  fluidRow(
    h4("Testing"),
    uiOutput("myfun"),
    tags$script("
    $(document).ready(function() {
      $('#Disable').click(function(){
      $('h4').css('display', 'none');
      });
})")
  )
)

shinyApp(ui, server = function(input, output) {
  
  output$myfun <- renderUI({
    
    tagList(
    actionButton("Disable", "Disable Element")
    )
    
  })
  
})

【问题讨论】:

    标签: r shiny


    【解决方案1】:

    一种选择是向按钮本身添加一个 onclick 事件。

    ui <- fluidPage(
      fluidRow(
        h4("Testing"),
        uiOutput("myfun"),
        tags$script("hideH4 = function() {$('h4').css('display', 'none');}")
      )
    )
    
    shinyApp(ui, server = function(input, output) {
      output$myfun <- renderUI({
        tagList(
          actionButton("Disable", "Disable Element", onclick="hideH4()")
        )
      })
    })
    

    或者为点击添加一个文档事件处理程序并检查 ID

    ui <- fluidPage(
      fluidRow(
        h4("Testing"),
        uiOutput("myfun"),
        tags$script("
        $(document).click(function(evt) {
          if (evt.target.id=='Disable') {
             $('h4').css('display', 'none');
          }})")
        )
    )
    
    shinyApp(ui, server = function(input, output) {
      output$myfun <- renderUI({
        tagList(
          actionButton("Disable", "Disable Element")
        )
      })
    })
    

    【讨论】:

    • 非常感谢。您的第二个解决方案对我有用。只是一个问题 - console.log(evt.target) 在控制台中没有返回任何内容?任何参考资料请详细阅读文档事件处理程序
    • 我删除了那个。我忘了它在那里。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-30
    • 1970-01-01
    • 2011-06-28
    • 2015-05-16
    • 2013-08-08
    • 1970-01-01
    相关资源
    最近更新 更多