我正在研究第一组 D3 教程(找到 here )并且遇到了数据数组的第一项没有出现的问题。我在每个数据 div 元素上放置的边框表示基本上第一个条目已“折叠”到顶部的一行中。是否有关于为什么会发生这种情况的解释?我怎样才能解决这个问题?
我的 HTML、CSS 和 JS 已经放到了codepen查看和编辑。
提前致谢!
独立的 JS:
var data = [10, 23, 14, 5, 6, 6, 6, 22, 17 ];
d3.select(".project")
.selectAll(".project__bar-chart")
.data(data)
.enter()
.append("div")
.attr("class", "project__bar-chart")
.style("width", function(d) {return d + "rem";})
.text(function(d) {return d;})
最佳答案
你的 HTML 中有这个:
<div class="project">
<div class="project__bar-chart"></div>
</div>
因此,当您这样做时:
d3.select(".project").selectAll(".project__bar-chart")
您正在选择一个以前存在的 <div>
在你的selectAll
,您的“输入”选择将少一个元素。
解决方案:删除类为project__bar-chart
的div :
<div class="project">
//look Ma, no div
</div>
这是你的笔:https://codepen.io/anon/pen/bgKxXG?editors=1010
这是一个堆栈片段:
var data = [10, 23, 14, 5, 6, 6, 6, 22, 17 ]; //The data that we're working with
d3.select(".project") //bring our focus to the container containing this class
.selectAll(".project__bar-chart")
.data(data) //the data is in line 1
.enter()
.append("div") // Shove the data (defined in line 1) into the Div in the HTML
.attr("class", "project__bar-chart")
.style("width", function(d) {return d + "rem";})
//we're inserting a function in this style attribute to make sure that the width of the div reflects the value given.
.text(function(d) {return d;}) //this is what it will look like
.project {
color: black;
font: 1rem;
font-family: sans-serif;
margin: .1rem:;
text-align: right;
}
.project__bar-chart {
background: #be3c3c;
border: 1px solid #802828
}
<head>
<script src="https://d3js.org/d3.v4.js"></script>
<script type="text/javascript" src="index.js"></script>
</head>
<body>
<div class="project">
</div>
关于javascript - D3 条形图不显示数组中的第一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42059135/