【发布时间】:2020-04-11 22:01:35
【问题描述】:
我正在创建一个使用 DataTable 的闪亮应用程序。我想为这个应用程序中的不同元素创建键盘快捷键,我可以。但是,只有在用户模糊了搜索栏时才应触发这些快捷方式。以另一种方式表达:如果搜索栏中的构建被聚焦,则不应激活快捷方式。
我尝试使用以下适用于标准输入字段的代码。由于某种原因,DataTable 搜索不计为输入字段,因为它不响应 js 代码。有谁知道对 DataTable 搜索栏进行焦点/模糊检查(onfocus 或 onblur 事件)的方法?
library(shiny)
library(DT)
library(shinyjs)
ui <- fluidPage(
useShinyjs(),
tags$script('$(document).on("keypress", function (e) {Shiny.onInputChange("keytyped", [e.which,e.timeStamp]);});'),
tags$script('$(document).ready(function() {
$("input").on("focus", function(){
Shiny.onInputChange("foc", 1);
});
$("input").on("blur", function(){
Shiny.onInputChange("foc", 0);
});
});'),
DT::dataTableOutput("datdata"),
textInput("test", "Test:")
)
server <- function(input, output, session) {
output$datdata <- DT::renderDataTable(mtcars
## THIS CALLBACK ONLY DOES SOMETHING WHEN SEARCHING! I NEED IT TO DO SOMETHING ON FOCUS!
# , callback = JS(
# 'table.on("search.dt", function(){
# Shiny.onInputChange("foc", 1);
# })'
# )
)
observe({
req(input$keytyped)
req(is.null(input$foc) | !input$foc)
## (Big letter codes) R = 82, S = 83, T = 84
check <- round(input$keytyped[1]) %in% c(82,83,84)
if(check){
print("ACTIVATE!")
}
})
# Print DataTable search and if input-fields are focussed.
observe(print(input$datdata_search))
observe(print(input$foc))
}
shinyApp(ui, server)
我知道上面的代码不是防弹的(键入“R”然后单击除测试字段“激活”快捷方式之外的任何其他位置),但我只是想提供一个小例子。
TLDR;是否可以让应用程序打印 1 或 0,具体取决于 DataTable 中的搜索栏是否聚焦。
编辑:SmokeyShakers 做到了我的要求。但我需要的一个补充是它应该只在搜索栏上,值应该改变。删除
tags$script('$(document).ready(function() {
$("#test").on("focus", function(){
Shiny.onInputChange("foc", 1);
});
$("#test").on("blur", function(){
Shiny.onInputChange("foc", 0);
});
});')
然后在解决方案代码中将“input”替换为“#datdata input”解决了我的问题!
【问题讨论】:
标签: javascript r shiny