我希望在单击时传递给特定伪类的元素的Shiny ID。如果UI元素是在Shiny应用程序的UI部分中创建的,那么一切正常。但是当在服务器端创建UI时(renderUI
),它不起作用。以下是可重现的例子。
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)
答案 0 :(得分:1)
$(document).ready
方法无法正常工作,因为在DOM准备好之前,服务器不会呈现输出。改为使用session$onFlushed
,once
参数设置为TRUE
,然后闪亮只运行一次,而不是每次会话刷新。
这将有效:
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)