简体   繁体   English

R 闪亮 - 最后点击的按钮 id

[英]R shiny - last clicked button id

I have multiple action buttons, on which i want to show different select Inputs and I want to know last clicked button id, how can I do that?我有多个操作按钮,我想在这些按钮上显示不同的选择输入,并且我想知道上次单击的按钮 ID,我该怎么做? When I use当我使用

which(lapply(c(1:10), function(i) { input[[paste0("ActionButton", i)]]}) == TRUE)

It shows me all button which were clicked, however I want to know which one was the last in order to enable click once again on previous buttons.它向我显示了所有被点击的按钮,但是我想知道哪个是最后一个,以便再次点击以前的按钮。 How can I do that?我该怎么做? I am new in shiny and not sure if understand all reactive/isolate issue so I would be greateful for any hints.我是闪亮的新手,不确定是否了解所有反应/隔离问题,所以我会很乐意提供任何提示。

You can do it by adding JS你可以通过添加JS来实现

smthing like有点像

$(document).on('click', '.needed', function () {
                              Shiny.onInputChange('last_btn',this.id);
                             });

Example ( add class needed to btn if you want to control not all btn)示例(如果您不想控制所有 btn,则将needed类添加到 btn)

 ui <- shinyUI(fluidPage(

  titlePanel("Track last clicked Action button"),
  tags$head(tags$script(HTML("$(document).on('click', '.needed', function () {
                                Shiny.onInputChange('last_btn',this.id);
                             });"))),

  sidebarLayout(
    sidebarPanel(
      actionButton("first", "First",class="needed"),
      actionButton("second", "Second",class="needed"),
      actionButton("third", "Third",class="needed"),
      actionButton("save", "save"),
      selectInput("which_","which_",c("first","second","third"))
    ),

    mainPanel(

      textOutput("lastButtonCliked")
    )
  )
))


server <- shinyServer(function(input, output,session) {
  observeEvent(input$save,{
    updateSelectInput(session,"which_",selected = input$last_btn)
  })
  output$lastButtonCliked=renderText({input$last_btn})

})
# Run the application 
shinyApp(ui = ui, server = server)

This code track which button was last clicked:此代码跟踪最后单击哪个按钮:

   library(shiny)


    ui <- shinyUI(fluidPage(


       titlePanel("Track last clicked Action button"),


       sidebarLayout(
          sidebarPanel(
            actionButton("first", "First"),
            actionButton("second", "Second"),
            actionButton("third", "Third")
          ),

          # Show a plot of the generated distribution
          mainPanel(
             textOutput("lastButtonCliked")
          )
       )
    ))


    server <- shinyServer(function(input, output) {

            rv <- reactiveValues(lastBtn = character())
            observeEvent(input$first, {
                    if (input$first > 0 ) {
                            rv$lastBtn = "first"
                    }
            })
            observeEvent(input$second, {
                    if (input$second > 0 ) {
                            rv$lastBtn = "second"
                    }
            })
            observeEvent(input$third, {
                    if (input$third > 0 ) {
                            rv$lastBtn = "third"
                    }
            })
            output$lastButtonCliked <- renderText({
                    paste("Last button clicked: ", rv$lastBtn)
            })
    })
    # Run the application 
    shinyApp(ui = ui, server = server)

Version with lapply with many buttons.带有许多按钮的 lapply 版本。 Credit goes to @Victorp and this answer .归功于@Victorp 和这个答案

This is the code:这是代码:

    library("shiny")
    ui <- fluidPage(
            fluidRow(
                    column(
                            width = 6,
                            lapply(
                                    X = 1:5,
                                    FUN = function(i) {
                                            actionButton(inputId = paste0("button", i), label = paste("Button ", i))
                                    }
                            )
                    ),
                    column(
                            width = 6,
                            textOutput("lastButtonCliked")
                    )
            )
    )
    server <- function(input, output){

            rv <- reactiveValues(lastBtn = character())

            lapply(
                    X = 1:6,
                    FUN = function(i){
                            observeEvent(input[[paste0("button", i)]], {
                                    if (input[[paste0("button", i)]] > 0) {
                                            rv$lastBtn = paste0("button", i)    
                                    }
                            })
                    }
            )

            output$lastButtonCliked <- renderText({
                    paste("Last button clicked: ", rv$lastBtn)
            })
    }
    shinyApp(ui = ui, server = server)

There is a third solution taking advantage of the fact that each button keeps the number of time is has been pressed.有第三种解决方案利用每个按钮保持被按下的次数这一事实。 If you could monitor that number of time, then any change in that number will indicate which button was pressed.如果您可以监控该时间数,那么该数字的任何变化都将表明按下了哪个按钮。

Here is a short implementation.这是一个简短的实现。 The page has three buttons (with arbitrary names):该页面具有三个按钮(具有任意名称):

page <- shinyUI(basicPage(
    actionButton("firstbtn",label="Btn1"),
    actionButton("secondbtn",label="Btn2"),
    actionButton("thirdbtn",label="Btn3"),
    textOutput("result")
))

shinyServer <- function(input, output, session) {
    # the number of clicks on each button is zero at first
    oldBtnClicks <- rep(0,3)

    observeEvent({ obs <<- list(input$firstbtn, input$secondbtn, input$thirdbtn) }, ({
        # store all button state in a list
        BtnState <- obs

        # extract in a vector the number of clicks from each
        newBtnClicks <- rep(0,3)
        for (i in 1:3) 
            newBtnClicks[i] <- if (is.null(BtnState[[i]])) 0 else BtnState[[i]][1]

        # look for the change in the number of clicks
        buttonClicked <- match(1, newBtnClicks - oldBtnClicks)

        # show the button number that was clicked
        output$result <- renderText(expr = buttonClicked)
        
        # update hte number of clicks in the shinyServer environment
        oldBtnClicks <<- newBtnClicks

    }))
}

shinyApp(ui = page, server = shinyServer)

The server function first set 0 to each button's click (they have not been pressed yet).服务器函数首先将每个按钮的点击设置为 0(它们还没有被按下)。 Then it sets and observer which looks for any of the button.然后它设置和观察者寻找任何按钮。 The list being observed could be of arbitrary length.被观察的列表可以是任意长度。

When an event occurs, the button states are retrieved in a list (the same as the observed list).当事件发生时,按钮状态在列表中检索(与观察列表相同)。 From that list, the first elements of each sublist is retrieved (this is the number of clicks on that particular button);从该列表中,检索每个子列表的第一个元素(这是该特定按钮的点击次数); if some buttons can be hidden (as was the case in my own application), the list of click is null and the number of click is therefore set to 0 manually.如果可以隐藏某些按钮(如我自己的应用程序中的情况),则单击列表为空,因此单击次数手动设置为 0。

Finally, by taking the difference between the former state and the new state, the only place which is not zero (found with match ) is the position of the button pressed.最后,通过取前一个状态和新状态之间的差异,唯一不为零的地方(找到match )是按下按钮的位置。 Once done, don't forget to update the button state list.完成后,不要忘记更新按钮状态列表。 Et voilà!等等!

If your buttons have a regular name (eg, BtnX, with X going from 1 to n), then there might be a way to built the observed list programmatically rather than by manually enumerating the buttons?如果您的按钮具有常规名称(例如,BtnX,X 从 1 到 n),那么可能有一种方法可以通过编程方式构建观察列表,而不是手动枚举按钮?

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

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