[英]Adding a Condition to Javascript in the Context of R Shiny DT Datatable
我想制作一個 javascript function 僅當滿足特定條件時才修改單元格的數據。 這是在 R Shiny 中的數據表的上下文中。目標是改進Stephane Laurent的這個巨大答案。
我不明白的是為什么要添加
if($cell.data.length > 10){...}
不起作用。 在 MWE 中,我將條件設置為 > 1 - 代碼適用於所有單元格。 如果將其設置為 > 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)
)
)
)
)
我編輯了另一篇文章來回答,但我可以在這里開發。
createdCell選項實際上是一個 function 和五個 arguments:
function(cell, cellData, rowData, rowIndex, colIndex) {
......
}
要定位包含超過 100 個字符的單元格,您可以執行以下操作:
function(cell, cellData, rowData, rowIndex, colIndex) {
if(cellData.length > 100) {
......
}
}
這應該與cell.data().length > 100
相同。
跳過第一行(記住索引在 JavaScript 中從 0 開始):
function(cell, cellData, rowData, rowIndex, colIndex) {
if(rowIndex > 0) {
......
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.