【问题标题】:Embedding javascript file within a shiny app www subdirectory does not work在闪亮的应用程序 www 子目录中嵌入 javascript 文件不起作用
【发布时间】:2021-07-04 11:04:00
【问题描述】:

似乎 Shiny 无法识别我的 .js 文件。问题是为什么?

内联js脚本文本运行流畅:

library(shiny)

header = dashboardHeader(disable = TRUE)
sidebar = dashboardSidebar(disable = TRUE)

body = dashboardBody(
    
    shiny::tags$script(
        HTML("document.body.style.backgroundColor = 'skyblue';")),
)

ui = dashboardPage(header = header, sidebar = sidebar, body = body)

server = function(input, output, session){

}
shinyApp(ui, server)

但是当我嵌入我的 .js 文件时(myscript.js 存储在 www 子目录中)

document.body.style.backgroundColor = "skyblue";

  $("firstinput").on("keypress", function(){
      alert("Pressed");
    })
  
  $(document).on('shiny:connected', function(event) {
  alert('Connected to the server'); 
    })

...像这样:

library(shiny)

header = dashboardHeader(disable = TRUE)
sidebar = dashboardSidebar(disable = TRUE)

body = dashboardBody(
    
    shiny::tags$head(
        shiny::tags$script(
            src = "myscript.js"
        )),
        
        HTML('<input type="button" id="firstinput">')
)

ui = dashboardPage(header = header, sidebar = sidebar, body = body)

server = function(input, output, session){
    
}
shinyApp(ui, server)

什么都没应用...怎么会?

【问题讨论】:

  • 请注意,$("firstinput") 应改为 $("#firstinput")。但我不认为这是问题的原因。您的代码应该可以工作。您是否在浏览器控制台中收到错误消息?
  • 你的权利,我已经尝试过$("#firstinput"),但它不起作用。当我使用 tags$script(src = "myscript.js") 而不是 tags$head 时,document.body.style.backgroundColor = "skyblue";$(document).on('shiny:connected', function(event) {alert('Connected to the server');}) 正在运行

标签: javascript html r shiny


【解决方案1】:

不需要tags$head()。以下工作正常。

tags$script(src = "myscript.js")

【讨论】:

  • 确实不需要tags$head,但我不明白为什么这会阻止代码工作。也许 $(document).ready 对于 JavaScript 的前两个语句是必需的,但第三个应该引发警报。没有?
  • 正如@StéphaneLaurent 提到的,我不明白为什么这会阻止代码工作。并且排除tags$head没有任何缺点,因为脚本没有嵌入到标题中?例如,当我嵌入其他 js 库(如 jBox)时,我也将它嵌入到带有 tags$head(tags$script(src = 'https://cdn.jsdelivr.net/gh/StephanWagner/jBox@v1.2.0/dist/jBox.all.min.js')) 的标头中,它工作得很好。
  • @StéphaneLaurent,你是对的。使用$(document).ready 可以很好地使用tags$head。他当前的myscript.js,如OP所示,只在没有tags$head的情况下有效。
猜你喜欢
  • 2020-09-09
  • 2016-01-06
  • 1970-01-01
  • 2018-12-06
  • 2021-06-01
  • 2014-03-26
  • 2021-11-12
  • 2019-01-08
相关资源
最近更新 更多