2017-01-06 42 views
0

閃亮的應用程序顯示一個句子。如何使用JavaScript更新閃亮的htmlOutput的內容

當用戶選擇句子的某個部分並單擊Mark按鈕添加標記時,應該更新該句子以反映該操作。

實施例:
樣品輸入:用於演示
選擇的樣品的句子:句子
希望的輸出:將試樣<markup> sentence for </markup>演示

以下是有光澤的應用程序代碼和相關的JavaScript代碼:

library(shiny) 
ui <- fluidPage(
    tags$head(tags$script(src="addMarkup.js")), 
    titlePanel("Mark text selection"), 
    mainPanel(htmlOutput("content"), 
     actionButton("Mark", "Mark", onclick="addMarkup()") 
    ) 
) 

server <- function(input, output) { 
    sentence <- "A sample sentence for demo" 
    output$content <- renderText(sentence) 
} 

shinyApp(ui = ui, server = server) 

addMarkup.js

function addMarkup(){ 
    var sent=""; 
    sent= document.getElementById("content").innerHTML; 
    var selection=""; 
    if(window.getSelection){ 
    selection = window.getSelection().toString(); 
    } 
    else if(document.selection && document.selection.type != "Control"){ 
    selection = document.selection.createRange().text; 
    } 
    marked = "<markup>".concat(selection).concat("</markup>"); 
    result = sent.replace(selection, marked); 
    alert(result); 
    document.getElementById("content").innerHTML = result; 
} 

問題:alert(result)它只表示期望的輸出,但隨後的線不更新content

如何實現此功能?

請同時建議是否存在一個純閃亮的解決方案(如何在不涉及JavaScript的情況下實現)。

回答

0

您的代碼正在工作。問題在於HTML中不存在<markup>標籤。如果您將<markup>更改爲<mark>,它將起作用。

marked = "<mark>".concat(selection).concat("</mark>"); 

enter image description here