如何遍历 d3 中的值内部数组并添加相应的子元素
How do I loop through an inner array of values in d3 and add corresponding children elements?
我有如下所示的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]; });
}
});
相关文章:
- 在函数中添加数组元素的数值
- 在Codrops的内容中添加数组元素展开缩略图网格预览
- 在javascript中动态添加数组数组
- 在 javascript 中添加数组到数组
- 如何使用推送在 JavaScript 中添加数组值
- 设置和添加数组值javascript时出现问题
- 使用 JavaScript 添加数组对象
- 将文件转换为数组并使用数据列表和选项标签为自动完成文本框添加数组元素
- 单击时将值推送到数组,然后循环添加数组值.Javascript
- 如何使用 JavaScript 更新或添加数组中的值
- 在窗体中动态添加数组文本框
- 在 javascript 中添加数组和对象会产生错误
- 如何在JavaScript中更新/添加数组的元素
- 在JavaScript中添加数组中的值
- 通过for循环添加数组值
- 如何在HTML中从Javascript添加数组的滚动列表
- Vaildate动态添加数组输入-jQuery Validate
- 在HighChart android中添加数组数据
- AngularJS:防止再次添加数组中已有的项
- 添加数组元素到现有的javascript数组