使用 D3.js 为每个数据成员附加多个非嵌套元素 [英] Appending multiple non-nested elements for each data member with D3.js
问题描述
我想使用 d3 创建多个非嵌套元素来创建这样的结构:
<p>来自数据[0]</p><p>来自数据[0]</p><p>来自数据[1] </p><p>来自数据[1] </p><p>来自数据[2] </p><p>来自数据[2] </p>
创建嵌套结构类似于
d3.select('#parent').selectAll('p').data(data).enter().追加('p')...追加('p')
但我想即使在追加之后仍保持原始选择,因此我可以继续追加到父元素.谢谢!
使用嵌套的惯用方式是:
var divs = d3.select('#parent').selectAll('p').data(data).enter().append('div');divs.append('p')divs.append('p')
创建:
<div><p>来自数据[0]</p><p>来自数据[0]</p><div><p>来自数据[1] </p><p>来自数据[1] </p>
<div><p>来自数据[2] </p><p>来自数据[2] </p>
如果这不起作用,请保存您的选择并重复追加:
var enterSelection = d3.select('#parent').selectAll('p').data(data).enter();enterSelection.append('p')enterSelection.append('p')
然后对您添加的内容进行排序:
d3.select('#parent').selectAll('p').sort(function(a, b){ return a.index - b.index; })
您需要向 data
的每个元素添加一个 index
属性来描述排序顺序.正常的 i
仅在特定选择的上下文中定义,当我们重新选择时会丢失.
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>
creating nested structures would go something like
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!
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')
Which creates:
<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; })
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屋!