在 RStudio 的文档中关于 shiny 中的 javascripts 事件 https://shiny.rstudio.com/articles/js-events.html , 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.
但是当我尝试在我 Shiny 的应用程序中使用第一种方法时,它似乎不起作用。
例如,如果您运行下面的应用程序,只有带有 $(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 方法应该有效。感谢任何帮助,谢谢
最佳答案
那是因为在读取脚本时该表还不存在(不在 DOM 中)。你可以这样做:
$(document).ready(function(){
$('#my_table').on('shiny:value', function(event) {
alert('MSG 1');
});
});
另一种可行的方法是将脚本放在 UI 的末尾,不带 tags$head
。
关于javascript - Shiny 的 Javascript 事件不适用于 $(#id) jQuery 选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71303444/