【问题标题】:Use SweetAlert2 in R Shiny在 R Shiny 中使用 SweetAlert2
【发布时间】:2017-02-13 12:21:09
【问题描述】:

我正在尝试使用 SweetAlert2 弹出窗口而不是传统的 JS 弹出窗口。期待一个示例来实现与我对 JS 概念的新手相同的效果。访问-https://sweetalert2.github.io/ 在实际场景中,我想在双击数据表行时使用这些 SweetAlert2 而不是 JS Alerts。

带有 JS 弹出窗口的代码:

library(shiny)
library(shinydashboard)
library(DT)

ui <- shinyUI(

dashboardPage (
    dashboardHeader(title="Report"),
    dashboardSidebar(sidebarMenu(menuItem("Table",tabName="Table"))),
    dashboardBody(      
        tabItems(
        tabItem(tabName = "Table",
            DT::dataTableOutput("DataTable")    
        )
   ))

))

server <- shinyServer(function(input, output) {
     output$DataTable <- DT::renderDataTable({
          datatable(iris,rownames=FALSE,selection = 'single',
                    options = list(
                              searching = FALSE,ordering=FALSE,
                              dom = 'Bfrtip',
                              buttons = c('copy','excel', 'pdf', 'print', 'colvis'),
                              columnDefs = list(list(visible=FALSE, targets=c(2))
          ),
     rowCallback = JS(
          "function(nRow, aData, iDisplayIndex, iDisplayIndexFull) {",
          "var full_text = aData[2]",
          # Tooltip for the rows
          "$('td:eq(1)', nRow).attr('title', full_text);",
          # Showing a hand as a cursor
          "$('td:eq(1)', nRow).css('cursor','pointer');",
          "$('td:eq(1)', nRow).css('font-weight','bold');",
          "}")
      ),
      #On double Click show Alert Message
     callback = JS('
          table.on("dblclick.dt","tr", function() {
          var data=table.row(this).data();
          alert("You clicked on "+data[4]+"\'s row");})
          '))
})
})

shinyApp(ui,server)

【问题讨论】:

    标签: r datatables shiny sweetalert sweetalert2


    【解决方案1】:

    我不熟悉那个 JS 库,无论如何这就是我认为应该工作的。

    ui.R

    首先你必须将js脚本添加到你的页面(注意路径,它应该是CDN/www/文件夹内的文件:

    tags$head(HTML("<script type='text/javascript' src='path/to/sweetAlert2.js'></script>"))
    

    服务器.R

    然后在你的回调中你可以调用库函数:

    callback = JS('
        table.on("dblclick.dt","tr", function() {
            var data=table.row(this).data();
            swal({
                title: "Click!",
                text: "You clicked on "+data[4]+"\'s row",
                type: "success",
                confirmButtonText: "Cool"
            })
        )')
    

    希望对你有帮助

    【讨论】:

    • 谢谢 Gamba。它有效!除了 JS 脚本,还添加了 SweetAlert 的 CSS 脚本以具有相同的外观和感觉。 CSS 部分 - tags$head( tags$link(rel = "stylesheet", type = "text/css", href = "sweetalert.css") )
    猜你喜欢
    • 2019-04-26
    • 1970-01-01
    • 1970-01-01
    • 2021-09-15
    • 1970-01-01
    • 2017-02-22
    • 2019-03-07
    • 2022-01-06
    • 2017-05-31
    相关资源
    最近更新 更多