我尝试在<{1}}上创建的一系列div
之前添加 兄弟姐妹。到目前为止,我有:
.enter()
这让我获得了所需的输出:
const data = [
{
"name": "foo",
"hierarchies": [
{
"name": "Alpha",
"children": [
{
"name": "A1"
},
{
"name": "A2"
},
],
"property": {
"name":"Sub-Alpha"
}
},
{
"name": "Bravo",
"children": [
{
"name": "B1"
},
{
"name": "B2"
},
],
"property": {
"name":"Sub-Bravo"
}
}
]
}
]
const system = d3.select('body').selectAll('div')
.data(data)
.enter().append('div').classed("system", true)
const hierarchy = system.selectAll('.system')
.data(function(d) { console.log(d.hierarchies); return d.hierarchies })
.enter().append('div').classed("hierarchy", true)
const children = hierarchy.selectAll('.hierarchy')
.data(function(d, i) { return d.children })
.enter().append('div').classed("child", true)
.text(function(d, i) { return d.name })
我需要从<div class="system">
<div class="hierarchy">
<div class="child">A1</div>
<div class="child">A2</div>
</div>
<div class="hierarchy">
<div class="child">B1</div>
<div class="child">B2</div>
</div>
</div>
插入.child
元素的兄弟,以获取它.text()
hierarchies.property.name
。预期的输出是:
<div class="system">
<div class="hierarchy">
<div class="property">Sub-Alpha</div>
<div class="child">A1</div>
<div class="child">A2</div>
</div>
<div class="hierarchy">
<div class="property">Sub-Bravo</div>
<div class="child">B1</div>
<div class="child">B2</div>
</div>
</div>
答案 0 :(得分:2)
您不需要插入兄弟姐妹,您可以继续使用append
的常规选择:
const property = hierarchy.selectAll('.property')
.data(function(d) {
return [d.property]
})
.enter().append('div').classed("property", true)
.text(function(d) {
return d.name
})
只需在const hierarchy
之后和const children
之前创建该选择。这会给你这个结构:
<div class="system">
<div class="hierarchy">
<div class="property">Sub-Alpha</div>
<div class="child">A1</div>
<div class="child">A2</div>
</div>
<div class="hierarchy">
<div class="property">Sub-Bravo</div>
<div class="child">B1</div>
<div class="child">B2</div>
</div>
</div>
以下是演示:
const data = [{
"name": "foo",
"hierarchies": [{
"name": "Alpha",
"children": [{
"name": "A1"
},
{
"name": "A2"
},
],
"property": {
"name": "Sub-Alpha"
}
},
{
"name": "Bravo",
"children": [{
"name": "B1"
},
{
"name": "B2"
},
],
"property": {
"name": "Sub-Bravo"
}
}
]
}]
const system = d3.select('body').selectAll('div')
.data(data)
.enter().append('div').classed("system", true)
const hierarchy = system.selectAll('.system')
.data(function(d) {
return d.hierarchies
})
.enter().append('div').classed("hierarchy", true)
const property = hierarchy.selectAll('.property')
.data(function(d) {
return [d.property]
})
.enter().append('div').classed("property", true)
.text(function(d) {
return d.name
})
const children = hierarchy.selectAll('.hierarchy')
.data(function(d) {
return d.children
})
.enter().append('div').classed("child", true)
.text(function(d) {
return d.name
})
&#13;
<script src="https://d3js.org/d3.v5.min.js"></script>
&#13;