简体   繁体   English

在 R Shiny DT 数据表的上下文中添加条件 Javascript

[英]Adding a Condition to Javascript in the Context of R Shiny DT Datatable

I would like to make a javascript function that modifies the data of a cell ONLY if a particular condition is met.我想制作一个 javascript function 仅当满足特定条件时才修改单元格的数据。 This is in the context of a datatable in R Shiny. The goal is to improve on this tremendous answer by Stephane Laurent .这是在 R Shiny 中的数据表的上下文中。目标是改进Stephane Laurent这个巨大答案

What I don't understand is why adding我不明白的是为什么要添加

  if($cell.data.length > 10){...}

doesn't work.不起作用。 In the MWE I've set the condition to > 1 - and the code works on all cells.在 MWE 中,我将条件设置为 > 1 - 代码适用于所有单元格。 If you set it to > 2, it does not work on any cells.如果将其设置为 > 2,则它不适用于任何单元格。

library(DT)
library(shinipsum)

text_df <- data.frame(
  numbers = 1:3,
  letters = LETTERS[1:3],
  text    = c(
    "Lorem", 
    substr(shinipsum::lorem, 1, 100), 
    substr(shinipsum::lorem, 1, 5000)
  )
)

js <- "
function(cell) {
  var $cell = $(cell);
  $cell.contents().wrapAll('<div class=\\\"content\\\"></div>');
  var $content = $cell.find('.content');
  if($cell.data.length > 1){
  $cell.append($('<button>Read more</button>'));
  $btn = $cell.find('button');
  $content.css({
    height: '20px',
    overflow: 'hidden'
  });
  $cell.data('isLess', true);
  $btn.click(function () {
    var isLess = $cell.data('isLess');
    $content.css('height', isLess ? 'auto' : '100px');
    $(this).text(isLess ? 'Read less' : 'Read more');
    $cell.data('isLess', !isLess);
  });
  } 
}
"
datatable(
  text_df,
  rownames = FALSE,
  options = list(
    "columnDefs" = list(
      list(
        "targets" = 2,
        "createdCell" = JS(js)
      )
    )
  )
)

I edited the other post to answer but I can develop here.我编辑了另一篇文章来回答,但我可以在这里开发。

The createdCell option actually is a function with five arguments: createdCell选项实际上是一个 function 和五个 arguments:

function(cell, cellData, rowData, rowIndex, colIndex) {
  ......
}

To target the cells containing more than 100 characters, you can do:要定位包含超过 100 个字符的单元格,您可以执行以下操作:

function(cell, cellData, rowData, rowIndex, colIndex) {
  if(cellData.length > 100) {
    ......
  }
}

That should be identical to cell.data().length > 100 .这应该与cell.data().length > 100相同。

To skip the first row (remembering that indexing starts at 0 in JavaScript):跳过第一行(记住索引在 JavaScript 中从 0 开始):

function(cell, cellData, rowData, rowIndex, colIndex) {
  if(rowIndex > 0) {
    ......
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM