Shiny Javascript 事件不适用于 $(#id) jQuery 选择器

Shiny Javascript Events not working with $(#id) jQuery selector

在 RStudio 关于闪亮 https://shiny.rstudio.com/articles/js-events.html 中的 javascripts 事件的文档中,shiny:value 事件有这个例子:

$('#foo').on('shiny:value', function(event) {
  // append a character string to the output value
  event.value += ' Oh that is nice!';
});

// use event.target to obtain the output element
$(document).on('shiny:value', function(event) {
  // cancel the output of the element with id 'foo'
  if (event.target.id === 'foo') {
    event.preventDefault();
  }
});

它说:

Since these events are triggered specifically on an output element, you may add the listener on the output element instead of on the document, although the latter also works, e.g.

但是当我尝试在我闪亮的应用程序中使用第一种方法时,它似乎不起作用。

例如,如果您 运行 下面的应用程序,只有带有 $(document) 选择器的方法有效并触发一条消息。

library(shiny)

ui <- fluidPage(
  tags$head(
    tags$script(
      "$('#my_table').on('shiny:value', function(event) {
        alert('MSG 1');
      });"
    ), 
    tags$script(
      "$(document).on('shiny:value', function(event) {
        if (event.target.id === 'my_table') {
          alert('MSG 2');
        }
      });"
    )
  ),
  
  sliderInput("my_slider", "Rows", 1, 20, 1),
  tableOutput("my_table")
)

server <- function(input, output, session) {
  output$my_table <- renderTable(iris[1:input$my_slider, ])
}

shinyApp(ui, server)

我想我遗漏了文档中的某些内容,它说 2 方法应该有效。感谢任何帮助,谢谢

那是因为在读取脚本时 table 不存在(不在 DOM 中)。你可以这样做:

$(document).ready(function(){
  $('#my_table').on('shiny:value', function(event) {
    alert('MSG 1');
  });
});

另一种可行的方法是将脚本放在 UI 的末尾,而不是 tags$head