【问题标题】:How can I set DataTables row callbacks in a Shiny R application?如何在 Shiny R 应用程序中设置 DataTables 行回调?
【发布时间】:2014-01-16 11:07:29
【问题描述】:

在 rCharts 中,可以使用特殊的字符串表示法设置 DataTables 的 JS 回调:#! function(par) {...} !#。例如,让我们看看下面的 R 代码:

  #JS callback to truncate long strings in table cells and add a tooltip
  callback = "#! 
  function (nRow) {
        $('td', nRow).each(function (index) {
            var maxChars = 80;
                var unfilteredText = $(this).text();
                if (unfilteredText.length > maxChars && maxChars > 3) {
                    $(this).attr('title', unfilteredText);
                    $(this).html(unfilteredText.substring(0, maxChars-4) + '...');
                }
        });
        return nRow;
    } !#"

  result <- dTable(df, aaSorting = list(c(5, "desc")), sPaginationType="full_numbers",
               fnRowCallback=callback)

这在 Shiny DataTables 中是否可行?

【问题讨论】:

标签: javascript r datatables shiny


【解决方案1】:

我只是偶然发现了这个问题,并且能够使用此处的信息以及this post 第 4.5 节的帮助来解决这个问题。为了让它工作,您只需执行以下操作:

library(DT)
long_strings = replicate(10, paste(sample(c(0:9, letters, LETTERS), 135, replace = TRUE), collapse = ""))
dat <- data.frame(x = 1:10, 
                  y = month.abb[1:10], 
                  z = long_strings, 
                  stringsAsFactors = FALSE)
DT::datatable(dat,
              options = list(
                rowCallback = JS("function(row, data) {",
                                 "  var max_chars = 80, full_text = data[3];",
                                 "    if (full_text.length > max_chars) {",
                                 "      $('td:eq(3)', row).attr('title', full_text);",
                                 "      $('td:eq(3)', row).html(full_text.substring(0, max_chars - 4) + '...');",
                                 "    }",
                                 "}")))

请务必注意,由于我们希望它以每行为基础进行操作,因此我们使用options 参数的inside 函数rowCallback。这与可以在整个表上使用的callback 函数形成对比,DT::datatable 是它自己的参数。

还请注意,您不必在data[3] 上致电.text().innerHTML 或类似的任何事情。返回的值是该单元格的文本值。

希望将来有人偶然发现这一点并发现它是有益的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-23
    • 2016-04-15
    • 1970-01-01
    • 2017-11-23
    • 2015-09-25
    • 2019-01-13
    相关资源
    最近更新 更多