我在构建R中的Shiny应用程序时遇到了这个问题。 在应用程序中,使用操作按钮来触发隐藏的下载按钮。 这样可以使我观察操作按钮事件,对该事件做出反应,然后触发下载过程。
但是,当我将下载按钮的display属性设置为hidden时,按钮的href目标(通常指向像"session/1c47..ef8/download/download_show?w="这样的东西)丢失了。
下面是一个更小的Shiny应用程序,重现了这个问题。
在应用程序中,两个操作按钮触发它们相应的下载按钮。点击可见的下载按钮会正确地下载文件
但是,当我将下载按钮的display属性设置为hidden时,按钮的href目标(通常指向像"session/1c47..ef8/download/download_show?w="这样的东西)丢失了。
下面是一个更小的Shiny应用程序,重现了这个问题。
shinyApp(
ui = fluidPage(
tags$head(
tags$style(HTML(".hide { display: none; }")),
tags$script(HTML('
Shiny.addCustomMessageHandler("trigger-button", function(message) {
document.getElementById(message.button_id).click();
});
'))
),
div(
class = "disable",
downloadButton("download_shown", "Shown"),
div(
class = "hide",
downloadButton("download_hidden", "Hidden")
)
),
br(),
actionButton("trigger_shown", "I can trigger the visible button!"),
actionButton("trigger_hidden", "I can trigger the hidden button!")
),
server = function(input, output, session) {
output$download_shown <- downloadHandler(
filename = "sample.txt",
content = function(file) {
cat("I'm visible!\n", file = file)
}
)
output$download_hidden <- downloadHandler(
filename = "sample2.txt",
content = function(file) {
cat("I'm hidden!\n", file = file)
}
)
observeEvent(input$trigger_shown, {
session$sendCustomMessage(
"trigger-button",
list(button_id = "download_shown")
)
})
observeEvent(input$trigger_hidden, {
session$sendCustomMessage(
"trigger-button",
list(button_id = "download_hidden")
)
})
}
)
在应用程序中,两个操作按钮触发它们相应的下载按钮。点击可见的下载按钮会正确地下载文件
sample.txt
。点击隐藏的下载按钮会下载一个HTML文件,即网页,而不是sample2.txt
文件。此外,如果检查生成的HTML,您会发现download_hidden
下载按钮具有没有目标的href属性。
- HTML规范中是否有任何规定隐藏元素不能有href目标?这似乎非常不可能,我搜索了很多也没有找到任何人或事情证实这一点。
- 内部上,Shiny是否忽略隐藏的元素?
- 在此期间,是否有人建议如何隐藏按钮而不使用
hidden
或display: none;
?
预先感谢你的帮助。