【发布时间】:2016-09-28 15:04:03
【问题描述】:
我正在使用rpivotTablehtmlwidget,它封装了出色的PivotTable.js 库。我想根据单元格的值有条件地格式化数据透视表。
为此,我尝试了调整函数here。这是一个带有rpivotTable 的最小闪亮应用程序:
rm(list = ls())
library(shiny)
library(shinydashboard)
library(rpivotTable)
library(dplyr)
#==========================================================
# simulate some data for the pivot table
#==========================================================
df_pivot = data_frame(
factor1 = sample(rep(LETTERS[1:2], 100)),
factor2 = sample(rep(LETTERS[5:6], 100)),
factor3 = sample(rep(LETTERS[19:20], 100)),
value = abs(rnorm(200))
)
#==========================================================
# ui
#==========================================================
pivot_body = dashboardBody({
tags$head(includeScript("pivot.js"))
tags$head(
tags$style(
HTML(
".realGone { background-color: #F08080 !important; }"
)
)
)
rpivotTableOutput(outputId = "pivot_output")
})
pivot_header = dashboardHeader(title = "Some title.")
pivot_sidebar = dashboardSidebar()
pivot_ui = dashboardPage(
header = pivot_header,
sidebar = pivot_sidebar,
body = pivot_body
)
#==========================================================
# server
#==========================================================
pivot_server = shinyServer(function(input, output, session) {
output$pivot_output = renderRpivotTable({
rpivotTable(
data = df_pivot,
rows = "factor1",
cols = "factor2"
)
})
})
#==========================================================
# run the app
#==========================================================
pivot_app = shinyApp(
ui = pivot_ui,
server = pivot_server
)
runApp(pivot_app)
这是我对 JS 函数的改编——基本思想是查找类为 .pvtVal 的元素,为它们添加一个类并基于该类应用 CSS 样式。
$(document).ready(function(){
var $labels = $('.pvtVal');
console.log("Reached here.");
for (var i=0; i<$labels.length; i++) {
if ($labels[i].innerHTML < 12) {
$('.pvtVal').eq(i).addClass('expired');
} else if ($labels[i].innerHTML > 12 && $labels[i].innerHTML < 14) {
$('.pvtVal').eq(i).addClass('dead');
} else if ($labels[i].innerHTML > 14) {
$('.pvtVal').eq(i).addClass('realGone');
}
}
});
但是当我检查控制台中的元素时,它们似乎没有添加 realGone 类。我的猜测是我误解了$document().ready 的作用。
【问题讨论】:
-
应该是
$( document ).ready()? (注意括号的位置) -
@warmoverflow 谢谢。已经解决了。但是添加的类仍然没有出现。它会出现在你面前吗?
-
@warmoverflow PS。对 JS 功能稍作改动,以备不时之需。
-
@warmoverflow 还尝试将函数绑定到
shiny:bound事件,但这似乎也不会触发 JS 函数。
标签: javascript jquery r shiny rpivottable