D3.js - 嵌套数据工作但选择不遵循

时间:2017-12-27 17:43:52

标签: d3.js

尝试理解如何处理D3中的嵌套数据我想出了这个例子:

<script>

data = [
{ Name: "jim", color: "blue", Points: [{x:0, y:5 }, {x:25, y:7 }, {x:50, y:13}] },
{ Name: "bob", color: "green", Points: [{x:0, y:10}, {x:27, y:30}, {x:57, y:60}] }
];

var print = function(d){d3.select("body li")
    .selectAll("b")
    .data(d)
    .enter()
        .append("b")
        .text(function(i){return ' - ' + i.x;});}

d3.select("body")
    .selectAll("li")
    .data(data)
    .enter()
        .append("li")
        .text(function(d){print(d.Points);});

</script>

我原以为这会产生这个:

<li>
  <b> - 0</b>
  <b> - 25</b>
  <b> - 50</b>
</li>
<li>
  <b> - 0</b>
  <b> - 27</b>
  <b> - 57</b>
</li>

而是产生以下内容:

<li>
  <b> - 0</b>
  <b> - 27</b>
  <b> - 57</b>
</li>
<li></li>

据我所知,当我选择“body li”时,我选择了两个现有的“li”,而我只给出了一个只有第一个“li”的“d”数据,但我真的不明白D3是如何工作的在这种情况下以及如何遍历“li”。

1 个答案:

答案 0 :(得分:2)

我首先创建li,然后使用绑定数据创建项目符号:

data = [
{ Name: "jim", color: "blue", Points: [{x:0, y:5 }, {x:25, y:7 }, {x:50, y:13}] },
{ Name: "bob", color: "green", Points: [{x:0, y:10}, {x:27, y:30}, {x:57, y:60}] }
];
//original selection creates two 'li' objects
var lines = d3.select("body")
    .selectAll("li")
    .data(data)
    .enter()
        .append("li");

//using the same selection; we can iterate (function(d,i) where i is the index) over each 'li' object
//to do so, we create a new selection where the data is pulled from the data in the 'lines' variable
var bullets = lines.selectAll('b')
    .data(function(d) { return d.Points; }) //returns the Points variable from the data already bound to the variable 'lines'
  .enter()
  .append('b')
  .text(function(d,i) {return ' - ' + d.x; }); //iterates (i) over each lines object and return the x variable from the bound data.