gpt4 book ai didi

javascript - 如何循环遍历 d3 中的内部值数组并添加相应的子元素?

转载 作者:行者123 更新时间:2023-12-02 14:44:06 25 4
gpt4 key购买 nike

我的 JSON 数据如下所示。

var data = [ 
{ animal: 'dog', names: [ 'mark', 'cooper', 'pooch' ] },
{ animal: 'cat', names: [ 'mary', 'kitty' ]
];

根据这些数据,我需要按以下方式使用 d3 生成 SVG 元素。

<svg id="mysvg" width="500" height="500">
<g data-animal="dog" transform="translate(0,0)">
<text x="10" y="10" fill="black">dog</text>
<text x="10" y="25" fill="black">mark</text>
<text x="10" y="40" fill="black">cooper</text>
<text x="10" y="55" fill="black">pooch</text>
</g>
<g data-animal="cat" transform="translate(0, 100)">
<text x="10" y="10" fill="black">cat</text>
<text x="10" y="25" fill="black">mary</text>
<text x="10" y="40" fill="black">kitty</text>
</g>
</svg>

要创建 g 元素,我执行如下操作。我保留 g 变量以附加更多元素。

var g = d3.select('#mysvg')
.selectAll('g')
.data(data)
.enter().append('g')
.attr({
'data-animal': function(d) { return d.animal; },
transform: function(d) { return 'translate(' + ... + ')'; }
});

现在我可以附加第一个 text 元素,如下所示。

g.append('text')
.attr({ x: '10', y: '10', fill: 'black' })
.text(function(d) { return d.animal; });

如何通过迭代每个 data[i].names 数组来向每个 g 附加更多元素?

最佳答案

一种方法是使用 .each函数对每个数据点进行操作。请注意,我们使用 d3.select(this) 来获取当前的 g。

 g.each(function(d) {
for(var i = 0; i < d.names.length; i++) {
d3.select(this).append('text')
.attr({ x: '10', y: '10', fill: 'black' })
.text(function(d) { return d.names[i]; });
}
});

关于javascript - 如何循环遍历 d3 中的内部值数组并添加相应的子元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36755257/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com