在另一篇文章中,假设该表不是renderUI函数的一部分,则回答了相同的问题。
在下面的示例中,我尝试调整相同的解决方案(使用JQuery),我要有条件地格式化的表属于renderUI函数。
library(shiny)
library(datasets)
script <- "$('tbody tr td:nth-child(5)').each(function() {
var cellValue = $(this).text();
if (cellValue > 50) {
$(this).css('background-color', '#0c0');
}
else if (cellValue <= 50) {
$(this).css('background-color', '#f00');
}
})"
shinyServer(function(input, output, session) {
session$onFlushed(function() {
session$sendCustomMessage(type='jsCode', list(value = script))
})
output$view <- renderTable({
head(rock, n = 20)
})
output$Test1 <- renderUI({
list(
tags$head(tags$script(HTML('Shiny.addCustomMessageHandler("jsCode", function(message) { eval(message.value); });'))),
tableOutput("view")
)
})
})
shinyUI(fluidPage(
tabsetPanel(
tabPanel("Test1",uiOutput("Test1")),
tabPanel("Test2")
)
))
Run Code Online (Sandbox Code Playgroud)
在此小示例中,条件格式未应用于表
通过添加参数将session$onFlushed每次调用shiny刷新函数,将您的调用更改为,以调用您的函数once = FALSE:
session$onFlushed(function() {
session$sendCustomMessage(type='jsCode', list(value = script))
}, once = FALSE)
Run Code Online (Sandbox Code Playgroud)
在一个独立的示例中:
library(shiny)
library(datasets)
script <- "$('tbody tr td:nth-child(5)').each(function() {
var cellValue = $(this).text();
if (cellValue > 50) {
$(this).css('background-color', '#0c0');
}
else if (cellValue <= 50) {
$(this).css('background-color', '#f00');
}
})"
runApp(list(server = function(input, output, session) {
session$onFlushed(function() {
session$sendCustomMessage(type='jsCode', list(value = script))
}, FALSE)
output$view <- renderTable({
head(rock, n = 20)
})
output$Test1 <- renderUI({
list(
tags$head(tags$script(HTML('Shiny.addCustomMessageHandler("jsCode", function(message) { eval(message.value); });')))
, tableOutput("view")
)
})
}
, ui = fluidPage(
tabsetPanel(
tabPanel("Test1",uiOutput("Test1")),
tabPanel("Test2")
)
))
)
Run Code Online (Sandbox Code Playgroud)
