You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

求助: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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 03:06:03