使用D3.js为每个数据成员附加多个非嵌套元素 [英] Appending multiple non-nested elements for each data member with D3.js
问题描述
我想使用d3创建多个非嵌套元素,以创建如下所示的结构:
I would like to create multiple non-nested elements using d3 to create a structure like this:
<div id="parent">
<p> from data[0] </p>
<p> from data[0] </p>
<p> from data[1] </p>
<p> from data[1] </p>
<p> from data[2] </p>
<p> from data[2] </p>
</div>
创建嵌套结构会像
d3.select('#parent').selectAll('p').data(data).enter().
append('p')...append('p')
想要保持原始选择,即使在追加之后,因此我可以继续追加到父元素。谢谢!
but I would like to maintain the original selection even after the append, so I could continue appending to the parent element. Thank you!
推荐答案
使用嵌套的
$ b
The idomatic way of doing is with nesting:
var divs = d3.select('#parent').selectAll('p').data(data).enter().append('div');
divs.append('p')
divs.append('p')
其创建:
<div id="parent">
<div>
<p> from data[0] </p>
<p> from data[0] </p>
</div>
<div>
<p> from data[1] </p>
<p> from data[1] </p>
</div>
<div>
<p> from data[2] </p>
<p> from data[2] </p>
</div>
</div>
如果这不起作用,请保存您的选择并重复附加:
If that won't work, save your selection and repeatedly append:
var enterSelection = d3.select('#parent').selectAll('p').data(data).enter();
enterSelection.append('p')
enterSelection.append('p')
然后排序您添加的内容:
then sort what you've added:
d3.select('#parent').selectAll('p').sort(function(a, b){ return a.index - b.index; })
您需要为描述排序顺序的 data
的每个元素添加 index
属性。正常 i
仅在特定选择的上下文中定义,当我们重新选择时会丢失。
You'll need to add an index
property to each element of data
that describes the sort order. The normal i
is only defined in the context of a particular selection, which is lost when we reselect.
这篇关于使用D3.js为每个数据成员附加多个非嵌套元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!