Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/r/77.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 将Shining app中的焦点设置为加载时的特定UI元素_R_Shiny - Fatal编程技术网

R 将Shining app中的焦点设置为加载时的特定UI元素

R 将Shining app中的焦点设置为加载时的特定UI元素,r,shiny,R,Shiny,在我的R Shining应用程序加载后,我想将焦点设置为selectInput元素,这样用户就可以立即通过上下箭头选择一个项目并按enter键 我试图捕获JavaScript加载事件,将其发送到R,然后使用shinny.addCustomMessageHandler设置selectInput元素的焦点 作为中间步骤,我还尝试使用actionButton中的click事件来触发元素焦点。虽然我认为大多数部分都应该在代码中,但load事件不会被传输到服务器,而焦点部分会被JavaScript获取 这

在我的R Shining应用程序加载后,我想将焦点设置为selectInput元素,这样用户就可以立即通过上下箭头选择一个项目并按enter键

我试图捕获JavaScript加载事件,将其发送到R,然后使用shinny.addCustomMessageHandler设置selectInput元素的焦点

作为中间步骤,我还尝试使用actionButton中的click事件来触发元素焦点。虽然我认为大多数部分都应该在代码中,但load事件不会被传输到服务器,而焦点部分会被JavaScript获取

这篇文章也没有帮助我到达终点线

这就是我到目前为止所做的:

library(shiny)
ui <- fluidPage(
  tags$head(tags$script('
    window.addEventListener("load", function(){
      alert("Loaded");
      Shiny.setInputValue("loaded", 1) // new identical function to Shiny.onInputChange
    });
 ')),
  tags$head(tags$script('
    Shiny.addCustomMessageHandler("focus", function(null) {
      document.getElementById("select").focus()
    });  
 ')),
  headerPanel("Focus",  windowTitle = "Focus"),
  fluidRow(
    column(width = 2, class = "panel",
           selectInput("select", label = "Your Choice", choices = c("Choice 1", "Choice 2"), selectize = TRUE),
           actionButton("click", "Click")
    ),
    column(width = 10,
           textOutput("text")
    )
  )
)

server = function(input, output, session) {

  observeEvent(input$loaded, {
    session$sendCustomMessage("focus",list(NULL))
    print("Loaded")
  })

  observeEvent(input$select, {
    print("Selected")
  })

  observeEvent(input$click, {
    session$sendCustomMessage("focus",list(NULL))
    print("Clicked")
  })

  output$text <- renderText({

  })
}

shinyApp(ui = ui, server = server)

谢谢你的帮助。

用Chrome打开控制台Ctrl+Shift+i,你会看到你的JS代码中有一些错误

最主要的一点是,当你打开应用程序时,shiny还没有准备好,因此找不到函数shinny.setInputValue

为确保已准备就绪,请使用:

$document.onshiny:已连接,函数{ ...... }; 现在,经过多次试验,我发现要聚焦的元素不是整个select元素。它是它的div子元素,带有selectize输入类,您可以使用$select~.selectize控件>.selectize输入进行选择

最后,要执行的好操作不是聚焦,而是单击。以下是完整的应用程序:

有光泽的图书馆
谢谢,这很有帮助!我正在查看元素的检查器,但是错误的控制台当然也非常有用。太糟糕了,所选的无法工作。如果该事件在移动selectInput中的上/下键时已经触发,甚至不点击enter键,那将非常好…实际上还有一个$select.change事件。。。但是我没有启动它。仅供参考,当我停用selectInput元素中的selectize选项时,$select.change事件也会起作用,即如果我将selectize设置为FALSE。当项目被选中一次时,每次鼠标上下移动都会触发另一个更改事件!