Ответ 1
Я смог понять это с помощью функции jQuery is(":focus")
, код, который я использовал, был:
$(document).keyup(function(event) {
if ($("#number").is(":focus") && (event.keyCode == 13)) {
$("#goButton").click();
}
});
Я пытаюсь написать функцию javascript, чтобы расширить демонстрацию демонстрационного экрана R <. Я хотел бы, чтобы пользователь мог ввести число, нажав кнопку действия и нажав кнопку ввода, когда они выбрали форму ввода номера. Код для ui.R:
shinyUI(pageWithSidebar(
headerPanel("actionButton test"),
sidebarPanel(
tags$head(tags$script(src = "enter_button.js")),
numericInput("number", "N:", min = 0, max = 100, value = 50),
br(),
actionButton("goButton", "Go!"),
p("Click the button to update the value displayed in the main panel.")
),
mainPanel(
verbatimTextOutput("nText")
)
))
и server.R:
shinyServer(function(input, output) {
ntext <- eventReactive(input$goButton, {
input$number
})
output$nText <- renderText({
paste(ntext(), input$goButton)
})
})
Я включил следующий javascript в файл с именем enter_button.js в папке www/
$("#number").keyup(function(event){
if(event.keyCode == 13){
$("#goButton").click();
}
});
Однако, когда я запускаю приложение, выберите форму ввода номера и нажмите кнопку действия, чтобы не активировать его, но он увеличивается, если я его нажму. В качестве альтернативы, я также проверил, как просто нажать кнопку ввода в любом месте документа:
$(document).keyup(function(event){
if(event.keyCode == 13){
$("#goButton").click();
}
});
и это сработало, поэтому я подозреваю, что jQuery не может найти элемент #number. Спасибо заранее!
Я смог понять это с помощью функции jQuery is(":focus")
, код, который я использовал, был:
$(document).keyup(function(event) {
if ($("#number").is(":focus") && (event.keyCode == 13)) {
$("#goButton").click();
}
});
Вот мое лучшее решение. Мне это не нравится tbh, но, по крайней мере, это работает.
library(shiny)
# This is a demo app to test a key binding on an actionButton
# Uncommenting the info item (on both UI and server) will display internal stuff
runApp(
list(
#############################################
# UI
#############################################
ui = bootstrapPage(
textInput ("myinput", label = "Write something here"),
tags$script('
$(document).on("keydown", function (e) {
Shiny.onInputChange("lastkeypresscode", e.keyCode);
});
'),
actionButton("GO", "Lancer le matching !"),
# verbatimTextOutput("info"),
verbatimTextOutput("results")
),
#############################################
# SERVER
#############################################
server = function(input, output, session) {
# There are state variables for the input text and GO button
curr.val <- "" # Corresponds to the current displayed input$myinput
curr.go <- 0 # Corresponds to the last known GO value (integer)
lastEvent <- reactive({
# Is reactive to the following events
input$GO
input$lastkeypresscode
# Decide which action should be taken
if(input$GO > curr.go) {
# The user pushed the GO actionButton, so take action
action <- 1
curr.go <<- input$GO
} else if(input$lastkeypresscode == 13) {
# The user pressed the Enter key, so take action
action <- 1
} else {
# The user did anything else, so do nothing
action <- 0
}
return(action)
})
output$results = renderPrint({
if(lastEvent() == 1) {
curr.val <<- isolate(input$myinput)
}
curr.val
})
# output$info = renderText({
# paste(curr.val, curr.go, input$lastkeypresscode, sep = ", ")
# })
}
)
)