簡體   English   中英

如何在閃亮的DT數據表中切換單元格類?

[英]How do I toggle a cell class in a shiny DT datatable?

我想使用Shiny和DT觸發數據表中特定單元格的事件。 假設我希望第一列在懸停時變為紅色。 創建表時,我添加了一個回調,該回調在第一列的td元素上注冊了一個懸停事件。

library(shiny)
library(DT)

ui <- fluidPage(
  tags$head(tags$style(HTML(".red { background-color: red; }"))),
  DT::dataTableOutput("iris")
)

server <- function(input, output) {
  output$iris <- DT::renderDataTable(DT::datatable(iris, callback = JS("
table.column(0).nodes().to$().hover(function(){$(this).toggleClass('red');});
")))
}

shinyApp(ui = ui, server = server)

從javascript控制台,如果我運行相同的代碼,則可以運行:

table=$('#DataTables_Table_0').DataTable()
table.column(0).nodes().to$().hover(function(){$(this).toggleClass('red');});

為什么這在datatable回調中不起作用? 什么是正確的方法?

通常,當您看到這種行為時,它暗示了時間問題。 在完全渲染表之前將回調該回調,您要對其進行操作的列還不存在。

刪除callback選項,並使用options = list( drawCallback = JS(...) )代替。

DT::datatable(
  iris,
  options = list(
    drawCallback = JS('function() {this.api().table().column(0).nodes().to$().hover(function(){$(this).toggleClass("red")}) }')
  )
)

為了完整drawCallback ,這里提供了三種解決方案: drawCallbackrowCallbacktable.on 上面給出了drawCallback作為答案。 columnDefs可用於將類分配給列,這使選擇器的使用變得容易。 rowCallbackdrawCallback的替代方法。 最后,可以使用datatables API中的on()為鼠標事件分配事件,但是您必須同時管理mouseentermouseleave而不是jQuery的hover()便捷方法。 (我發現這最后一個解決方案很困惑,因為文檔(1)沒有第二個選擇器參數, (2)鼠標事件未在events API中列出,但這是可行的!)

重要的是,只需要其中之一,而不是全部三個! 就個人而言,我最喜歡rowCallback

library(shiny)
library(DT)

ui <- fluidPage(
  tags$head(tags$style(HTML(".red { background-color: red; }"))),
  div(id='tbl1', DT::dataTableOutput("iris"))
)

server <- function(input, output) {
  output$iris <- DT::renderDataTable(DT::datatable(iris, 
                                                   options = list(drawCallback=JS("function() { this.api().table().column(0).nodes().to$().hover(function(){$(this).toggleClass('red');}); }"),
                                                                  rowCallback=JS("function(row) { $(row).children('.firstcol').hover(function(){$(this).toggleClass('red')}) }"),
                                                                  columnDefs=list(list(className='firstcol', targets=0))),
                                                    callback = JS("
 table.on('mouseenter', 'td.firstcol', function() { $(this).addClass('red'); });
 table.on('mouseleave', 'td.firstcol', function() { $(this).removeClass('red'); });
")))
}

shinyApp(ui = ui, server = server)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM