gpt4 book ai didi

javascript - 来自 JSON 文件的 D3.js HTML 表格——如何创建空值以便不丢失 元素?

转载 作者:可可西里 更新时间:2023-11-01 14:44:20 25 4
gpt4 key购买 nike

我使用 d3.js 从 JSON 文件创建了一个 html 表。它显示每个国家/地区每年的值(value)。它有点管用。每个国家/地区的值都 float 到左侧。因此,如果特定年份没有值,则其他年份的值将移至其位置。 (看看这个 plunker,一旦你看到它就更有意义了——底部表格行就是问题所在。)

所以我的问题是:如何为这些实例生成空值/空单元格,以便表格正确读取?这可能吗?

代码在下面,这里是一个 plunker .

    <!DOCTYPE html>
<html>
<head>
<style>
body{
font-family:Arial, sans-serif;
font-size:14px;
}
table{
border-spacing:0;
padding:0;
}
#buildcontent{
width:65%;
float:left;
margin-left:20px;
margin-top:20px;
}
#buildcontent table#years{
clear:both;
}
#buildcontent table#years td{
width:30px;
padding-left:5px;
padding-right:35px;
}
#buildcontent table#countries{
width:100%;
}
table#years td{
border-top:1px solid #ddd;
border-bottom:0px;
font-weight:bold;
padding-left:5px;
padding-top:3px;
height:18px
}
th{
text-align:left;
font-weight:normal !important;
border-top:1px solid #ddd;
border-left:1px solid #ddd;
border-bottom:1px solid #ddd;
height:25px;
padding-left:5px;
width: 200px;
}
td{
border:1px solid #ddd;
width:30px;
height:25px;
padding-left:5px;
}
tr.row-odd,
.row-odd{
background: #eee;
}
</style>
<script src="http://d3js.org/d3.v3.min.js"></script>
<script src="//code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<div id="buildcontent">
<table>
<thead id="years">
</thead>
<tbody id="countries">
</tbody>
</table>
</div>
<script>

d3.json("data.json", function(json) {
json.forEach(function(d){
d.value = Math.round((+d.value + 0.00001) * 1000) / 1000;
});

var nestfilt = d3.nest()
.key(function(d) { return d.country; })
.sortKeys(d3.ascending)
.map(json);

// add years
var nestyr = d3.nest()
.key(function(d) { return d.year; })
.sortKeys(d3.ascending)
.map(json);

var yearstring = Object.keys(nestyr);

var row = document.getElementById("years");
row.appendChild(document.createElement("td"));

yearstring.forEach(function (yr) {
var td = document.createElement("td");
td.textContent = yr;
row.appendChild(td);
});

var tr = d3.select("#countries")
.selectAll("tr")
.data(d3.entries(nestfilt));

tr.enter().append("tr");

// add stripes to the table
tr.attr("class", function(d, i){ if (i++ % 2 === 0){return 'row-even'}else {return 'row-odd'}});

var col1 = tr.append("th")
.html(function(d) { return d.key; })
.attr("id", "country");

var cells = tr.selectAll("td")
.data(function(d) { return d.value; });

cells.enter().append("td");
cells.text(function(d) { return d.value; });

tr.exit().remove();
cells.exit().remove();

});

</script>
</body>
</html>

缺少单元格的行的屏幕截图: Rows with missing cells

最佳答案

您可以做的一件简单的事情是创建一个小函数来查看单元格的内容是否为空,如果为空(给定年份的值不存在),则使单元格的内容“不可用”或 ""而不是将其留空。希望能帮助到你。 :)

关于javascript - 来自 JSON 文件的 D3.js HTML 表格——如何创建空值以便不丢失 <td> 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32706080/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com