HTML文件与Shiny中编写JS/HTML代码的差异及运行问题求解
问题说明
直接写入.html文件可正常运行的原生HTML代码如下:
<h1>Change the HTML content</h1> <h2 id="hcontent">Hello Manu</h2> <h3>Welcome</h3> <button type="button" onclick="document.getElementById('hcontent').innerHTML='Hello Mr. Manu'">Click here</button>
将相同逻辑迁移到Shiny应用时代码失效,原始Shiny代码存在两个问题:
- 引号嵌套冲突:内联
onclick事件的属性值用单引号包裹,但内部JS代码也使用了单引号,浏览器解析时会提前截断属性值,导致JS逻辑完全跑不起来 - 内容放错位置:需要展示给用户的标题、按钮等正文内容被错误塞到了
tags$head()里,<head>节点是存页面元数据、引静态资源的地方,里面放的正文内容不会正常显示在页面可视区域
修复方案
方案1:修正原生HTML写法(最小改动)
把正文内容从tags$head()中移出,同时转义冲突的引号即可,可直接运行的代码如下:
library(shiny) ui <- fluidPage( HTML(" <h1>Change the html content</h1> <h2 id='hcontent'>Hello Vinay</h2> <h3>Welcome</h3> <button type='button' onclick=\"document.getElementById('hcontent').innerHTML='Hello Mr Vinay'\">Click here</button> ") ) server <- function(input, output, session) { } shinyApp(ui, server)
方案2:使用shinyjs符合Shiny开发规范
不写内联JS,用shinyjs提供的方法操作DOM,代码可读性更高,也能避免引号转义问题:
library(shiny) library(shinyjs) ui <- fluidPage( useShinyjs(), h1("Change the html content"), h2(id = "hcontent", "Hello Vinay"), h3("Welcome"), actionButton(inputId = "change_text", label = "Click here") ) server <- function(input, output, session) { observeEvent(input$change_text, { html(id = "hcontent", html = "Hello Mr Vinay") }) } shinyApp(ui, server)
内容的提问来源于stack exchange,提问作者manu p
相关产品推荐
相关产品推荐

