求助:R Shiny中DataTable列名按钮绑定bsPopover无法触发问题
问题根因
shinyBS的bsPopover仅会在页面首次加载时,为当时已经存在的DOM元素绑定悬浮提示事件- DT表格属于异步渲染组件,页面初始加载完成后才会渲染表格内容(包括列名里的自定义按钮),因此初始绑定时找不到你写在列名里的
notWorking按钮,悬浮提示自然无法触发
修复方案
在DT渲染完成的回调中手动绑定popover即可,不影响原有列头排序功能,修改后可直接运行的代码如下:
library(shiny) library(shinyBS) library(DT) library(dplyr) ui <- fluidPage( titlePanel('Making a Popover Work in DataTable'), mainPanel( fluidRow( # 正常工作的外部popover p(bsButton("workingPop", label = "", icon = icon("question"), style = "info", size = "extra-small") ), bsPopover(id = "workingPop", title = "This Popover Works", content = "It works very well", placement = "right", trigger = "hover", options = list(container = "body") )), fluidRow(dataTableOutput('myTable')) ) ) server <- function(input, output, session) { output$myTable <- DT::renderDataTable({ datatable(mtcars %>% rename("hp <button type='button' id='notWorking' class='btn action-button btn-info btn-xs shiny-bound-input'> <i class='fa fa-question' role='presentation' aria-label='question icon'></i> </button>"=hp), rownames=TRUE, selection='none', escape=FALSE, options = list( initComplete = JS( "function(settings, json) {", "$('#notWorking').popover({", "title: 'This one now works',", "content: 'I\\'d like to give information about hp: it means horsepower. I want a popover, because my real example has lot\\'s of text.',", "placement: 'top',", "trigger: 'hover',", "container: 'body'", "});", "}" ) ) ) }) } shinyApp(ui = ui, server = server)
核心改动点
- 移除了ui中无效的列按钮对应
bsPopover声明,初始加载时按钮不存在,该声明不会生效 - 在
datatable的initComplete配置项中添加JS回调,DT完全渲染完成后才会执行popover绑定逻辑 - 补全了
dplyr依赖,避免原代码中rename函数运行报错
内容的提问来源于stack exchange,提问作者Patrick
相关产品推荐
相关产品推荐

