作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的 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/
我在 Java 中遇到异常处理问题,这是我的代码。当我尝试运行此行时出现编译器错误:throw new MojException("Bledne dane");。错误是: exception MojE
我刚刚开始学习asp.net。在你们的支持下,我希望我能从这个论坛学到更多东西。 我的问题是, 我在 asp.net 页面中有一个 TabContainer1,因为每个选项卡面板中有多个类似 (60)
我是一名优秀的程序员,十分优秀!