javascript – 通过在Shiny App的服务器部分中创建的jQuery UI元素进行访问

我想在点击时传递给特定伪类元素的Shiny ID.如果UI元素是在Shiny应用程序的UI部分中创建的,那么一切正常.但是当在服务器端(通过renderUI)创建UI时,它不起作用.以下是可重复的例子.

library(shiny)
library(shinyjs)

ui <- fluidPage(
  useShinyjs(),
  fluidRow(
    tags$div(id = "ui1", class = 'shiny-html-output shiny-bound-output',
      tags$a(id = "ID1", class = "my-class", href = "#", 'Link 1')
    ),
    uiOutput("ui2")
  )
)

server <- function(input, output) {
  output$ui2 <- renderUI({
    tags$a(id = "ID2", class = "my-class", href = "#", 'Link 2')
  })

  shinyjs::runjs(
  '$(document).ready(function(){
    $(".my-class").click(function(){
      alert($(this).attr("id"));
    });
  });')
}

shinyApp(ui, server)

最佳答案 $(document).ready方法将无法工作,因为在DOM准备好之前,服务器不会呈现输出.使用session $onFlushed,一旦参数设置为TRUE,则shiny将仅运行一次该函数,而不是每次会话刷新.

这将有效:

library(shiny)
library(shinyjs)

script <- "$('.my-class').click(function(){
alert($(this).attr('id'));
});"

ui <- fluidPage(
  useShinyjs(),
  fluidRow(
    tags$div(id = "ui1", class = 'shiny-html-output shiny-bound-output',
             tags$a(id = "ID1", class = "my-class", href = "#", 'Link 1')
    ),
    uiOutput("ui2")
  )
)

server <- function(input, output, session) {

  output$ui2 <- renderUI({
    tags$a(id = "ID2", class = "my-class", href = "#", 'Link 2')
  })


  session$onFlushed(function() {
    shinyjs::runjs(script)
  }, once=TRUE)

}

shinyApp(ui, server)
点赞