我正在创建一个基于Jonah表格的交互式表格:http://bl.ocks.org/jonahwilliams/cc2de2eedc3896a3a96d
我希望符合特定条件的单元格为绿色,不符合标准的单元格为红色。开关是我放在左上角的选择器菜单。如果我为thead单元格运行此代码“th”一切正常,但如果我为tbody单元“td”执行此操作则无效。
<!DOCTYPE html>
<meta charset="utf-8">
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css">
<style>
#table-location {
margin-left: 0;
margin-right: auto;
width: 70%;
}
</style>
</head>
<body>
<select id="selector"></select>
<div id="table-location"></div>
<script src="https://d3js.org/d3.v4.min.js"></script>
<script>
// var svg = d3.select("body").append("svg")
// .attr("height", 1)
// .attr("width", 19);
var table = d3.select("#table-location")
.append("table")
.attr("class", "table table-condensed table-striped"),
thead = table.append("thead"),
tbody = table.append("tbody");
d3.tsv("VotingInformationTable.tsv", function(error, data2){
// }
// // filter year
// var data1 = data2.filter(function(d){return d.Year == '2010';});
// // Get every column value
var columns = Object.keys(data2[0]);
// .filter(function(d){
// return ((d != "Year"));
// });
var header = thead.append("tr")
.selectAll("th")
.data(columns)
.enter()
.append("th")
.text(function(d){ return d;})
.on("click", function(d){
if (d == "Year"){
rows.sort(function(a, b) {
if (a[d] < b[d]){
return -1;
}
if (a[d] > b[d]){
return 1;
}
else{
return 0;
}
});
}
else {
rows.sort(function(a, b){
return b[d] - a[d];
})
}
});
var rows = tbody.selectAll("tr")
.data(data2)
.enter()
.append("tr")
.on("mouseover", function(d){
d3.select(this)
.style("background-color", "orange");
})
.on("mouseout", function(d){
d3.select(this)
.style("background-color","transparent");
});
var cells = rows.selectAll("td")
.data(function(row){
return columns.map(function(d){
return {value: row[d]};
});
})
.enter()
.append("td")
.html(function(d){ return d.value;});
var players = d3.nest()
.key(function(d){ return d.Year; })
//.key(function(d){return d.Club;})
//.key(function(d){return d.PointsNTeams;})
//.rollup(function(d){ return d.PointsNTeams; })
.rollup(function(a){ return a.length; })
.entries(data2);
var selector = d3.select("#selector");
selector
.selectAll("option")
.data(players)
.enter()
.append("option")
.text(function(d){ return d.key + ":" + d.value; })
.attr("value", function(d){ return d.key; })
selector
.on("change", function(d){
d3.selectAll("th")
.style("color", function(d)
{
if (d == "Year") {
return "green";
}
else {
return "red";
}
});
});
});
</script>
</body>
答案 0 :(得分:0)
您可以使用以下颜色对与所选年份对应的行进行着色:
selector
.on("change", function(d){
var v=this.value;
rows.style("color", function(d){
if (d.Year == v){
return "green";
}
else { return "red";}
});
});