D3.js - 嵌套数据的作品,但选择不遵循
试图了解如何应对D3嵌套数据,我想出了这个例子:js" title="D3.js">D3.js - 嵌套数据的作品,但选择不遵循
<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>
我明白,当我选择“身体里”我本身将现有的两个“li”放在一起,我只给出一个只在第一个“li”中出现的“d”数据,但我真的不明白D3如何在这种情况下工作以及如何遍历“li”。
回答:
我创建li
第一,然后使用绑定的数据来创建子弹:如果你使用`each`并通过`
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.
以上是 D3.js - 嵌套数据的作品,但选择不遵循 的全部内容, 来源链接: utcz.com/qa/266688.html