D3 条形图未显示数组中的第一个元素

3
我正在制作第一组D3教程(在这里找到),遇到了一个问题,即数据数组的第一项未显示。我放置在每个数据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;}) 

1
删除您<div class="project">内部的<div>标签。 - user5734311
1个回答

5
您的HTML中有以下内容:

您在HTML中拥有:

<div class="project">
  <div class="project__bar-chart"></div>
</div>

因此,当你执行以下操作时:

d3.select(".project").selectAll(".project__bar-chart")

您正在选择先前存在的一个<div>在您的selectAll中,您的“enter”选择将少一个元素。
解决方案:删除类为project__bar-chart

<div class="project">
    //look Ma, no div
</div>

这是您的笔: https://codepen.io/anon/pen/bgKxXG?editors=1010 以下是一个 Stack 代码片段:

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>


非常感谢!您提供的文档也非常有帮助。 - Libby B

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接