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

如何点击DT单元格内图标时避免选中对应行?

解决Shiny DT表格点击展开图标时选中行的问题

点击展开/收起图标时行被选中,是因为点击事件会向上冒泡到表格行元素,触发了DT默认的行选中行为。要避免这个问题,只需要在图标的点击事件中阻止事件冒泡即可。

修改后的完整代码如下:

library(shiny)
library(DT)
li <- "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum"
data <- data.frame(
  ID = 1:3,
  Description = rep(li, 3)
)

ui <- fluidPage(
  DTOutput("mytable")
)

server <- function(input, output) {
js <- JS(
  "function(data, type, row, meta) {
     if (type === 'display' && data.length > 40) {
       var truncated = data.substr(0, 38) + '...';
       var fullText = data;
       return '<span class=\"truncate\">' + truncated + '</span>' +
              '<span class=\"hidden-text\" style=\"display:none;\">' + fullText + '</span>' +
              '<span class=\"expand-icon\" style=\"cursor:pointer;\" onclick=\"' +
              'event.stopPropagation(); ' + // 阻止事件冒泡,避免行被选中
              'var icon = $(this); ' +
              'icon.prev().toggle(); ' +
              'icon.text(icon.text() === \\'▼\\' ? \\'▲\\' : \\'▼\\');' +
              '\">▼</span>'; 
     } else {
       return data;
     }
   }"
)
  
  output$mytable <- renderDT({
    datatable(data, escape = FALSE, options = list(columnDefs = list(
      list(targets = 2, render = js)
    )))
  })
}

shinyApp(ui, server)

关键改动说明

在图标的onclick事件开头添加event.stopPropagation();,这个方法会阻止当前事件向父级元素传播,这样点击图标的操作就不会触发表格行的选中事件了。

内容的提问来源于stack exchange,提问作者Ferroao

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 06:16:17