javascript - 使用 Javascript 在 Shiny 应用程序中删除 DataTable 行
问题描述
我正在尝试使用 Javascript 从 Shiny 应用程序中的数据表中删除行。在表中,我有一列,每行都有一个“删除”按钮。这或多或少是我想要做的,但我无法让它发挥作用。
在我的 server.R 中:
initComplete <- DT::JS(
"function () {",
" var table = this.api();",
" $('#delete_button').on('click', function() {",
" table.row($(this).parents('tr')).remove().draw();",
" });",
"}"
)
shinyInput <- function(FUN, len, id, ...) {
inputs <- character(len)
for (i in seq_len(len)) {
inputs[i] <- as.character(FUN(paste0(id, i), ...))
}
inputs
}
output$under_list <- renderDataTable({
list_under <- getListUnder() # this is a reactive
list_under$Delete <- shinyInput(actionButton, nrow(list_under),'delete_',label = "Delete",icon=icon("trash"),
style = "color: red;background-color: white",
onclick = paste0("Shiny.setInputValue( \"delete_button\" , this.id, {priority: \"event\"})"))
table <- list_under %>%
DT::datatable(filter = "none", rownames = F
,extensions = 'FixedColumns'
,options = list(pageLength = 10,scrollX = TRUE,
fixedColumns = list(leftColumns = 2),
initComplete = initComplete),
escape=F
) %>%
formatCurrency(c(5,8,9,11,15),digits=2,currency='€') %>%
formatPercentage(13:14)
})
解决方案
library(DT)
library(shiny)
rowNames = FALSE # whether to show row names
colIndex <- as.integer(rowNames)
dat = iris[1:5,]
dat[["Action"]] <- vapply(seq_len(nrow(dat)), function(i){
as.character(tags$button("delete", id = paste0("delete-",i), `data-index` = i))
}, FUN.VALUE = character(1L))
dat[["rowId"]] <- paste0("row-", seq_len(nrow(dat)))
callback <- JS(
'$("button[id^=delete]").on("click", function() {',
' var index = $(this).data("index");',
' var rowId = "#row-" + index;',
' table.row(rowId).remove().draw();',
'});'
)
datatable(
dat,
rownames = rowNames,
escape = -ncol(dat)+1L,
callback = callback,
options = list(
rowId = JS(sprintf("function(data){return data[%d];}",
ncol(dat)-1L+colIndex)),
columnDefs = list(
list(visible = FALSE, targets = ncol(dat)-1L+colIndex),
list(className = "dt-center", targets = "_all")
)
)
)
推荐阅读
- ruby-on-rails - 服务器端在 Rails 中渲染反应组件的简单方法是什么?
- c# - 从 appsettings 设置应用程序的 url
- image - 使用个人资料图片注册 Azure Active Directory B2C 本地帐户
- css - 如何将 facebook 嵌入视频设置为 100% 宽度
- node.js - CORS 阻止来自 Dockerized React 项目的 API 调用
- android - AWS Cognito - 社交登录选项行为
- git - Github 上的远程分支不允许删除
- json - 当 json 对象键为单个字符长度时,th:text 表达式不计算 json 字符串
- php - PHP中的变量如何存储在类中?
- java - 我怎么知道 JVM 错误已在较新版本中得到解决?