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

标签 javascript r shiny

在 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/

相关文章:

javascript - Jquery SlideDown()

javascript - 复制特定文本以复制javascript中的另一个文本

r - 在条形图中添加两条垂直线

javascript - 在 Chrome 中重新加载动画 GIF 时出现问题 - 第二部分

r - 如何在R中的粘贴功能中加粗文本并使用字体

javascript - 如何合并多边形并移除重叠部分?

javascript - SVG 在 IE 上无法正确渲染

r - 获取Rook/Shiny页面用户的私有(private)IP地址

r - 将向量解包到列表中,向量的每个元素作为列表中的单独元素

r - Shiny 的观察者响应所有未选中的复选框