【问题标题】:for loop in Shiny htmlOutput does not execute in orderShiny htmlOutput中的for循环没有按顺序执行
【发布时间】:2016-11-11 18:00:35
【问题描述】:

在 Shiny htmlOutput 中使用循环是一种非常奇怪的行为。我一直在尝试做的非常简单,从 Shiny htmlOuput 执行 Javascript 代码(console.log)并将循环编号打印到控制台。见以下代码:

library(shiny)
ui <- fluidPage(
  actionButton("goButton", "Go!"),
  mainPanel(htmlOutput("result"))
)
server<-  function(input, output) {
  observeEvent(input$goButton,{
    output$result <- renderUI({
      html_output_list <- lapply(1:50, function(j) {
        htmlname <- paste("html", j, sep="")
        htmlOutput(htmlname)
      })
      # Convert the list to a tagList - this is necessary for the list of items
      # to display properly.
      do.call(tagList, html_output_list)
    })
    lapply(1:14, function(i){ 
        htmlname <- paste("html", i, sep="")
        output[[htmlname]] <- reactive({
          paste('<script>number=',
                            i,
                            ';console.log(number);</script>')
          })
        })
    })
}
shinyApp(ui = ui, server = server)

通过单击 go 按钮,结果应该是从 1 到 14 的有序序列号(因为数字 i 从 1 到 14 循环),但实际结果是 14,1,2,...,13。尝试从 1:20 开始的 i 范围将生成一个序列为 (14,15,16,17,18,1,19,2,3,4,5,6,7,8,20,9,10,11 ,12,13)​​。谁能解释这里发生了什么?怎么不按顺序?显然这不是随机顺序。

【问题讨论】:

    标签: javascript r shiny


    【解决方案1】:

    也许这会有所帮助:

    应用程序:R

       library(shiny)
        library(shinyjs)
        ui <- tagList(
                useShinyjs(),
                fluidPage(
                actionButton("goButton", "Go!"),
                mainPanel(
                         uiOutput("result")
        )))
        server<-  function(input, output) {
    
                observeEvent(input$goButton, {
                    lapply(1:50, function(j){
    
                            shinyjs::logjs(paste('number=', j))
                        })
    
                })
    
        }
        shinyApp(ui = ui, server = server)
    

    【讨论】:

    • 这可能会给出正确的答案,但它与我的目的略有不同。您通过在输出之前将 Javascript 分配给数组 (x) 来完成循环。是否可以在循环内输出?我的代码是为了实现这一点,但执行顺序不正确。谢谢。
    • 尝试使用 shinyjs 包和 logjs 功能。检查修改后的答案。
    猜你喜欢
    • 2017-02-22
    • 1970-01-01
    • 2019-06-16
    • 1970-01-01
    • 2020-08-30
    • 2018-03-24
    • 2014-05-29
    • 2021-08-09
    • 2020-04-09
    相关资源
    最近更新 更多