我是 d3.js
的初学者,在使用 d3.v3
创建图表时遇到了一个奇怪的问题。我想念带有 index 0
的节点。
这是console.log(gnode)
的输出:
[Array(4)]
0: Array(4)
0: null
1: g
2: g
3: g
parentNode: g
length: 4
__proto__: Array(0)
length: 1
__proto__: Array(0)
这是我的代码:
var svg_graph = svg.append('svg:g')
var vis = svg_graph.append("svg:g");
gnode = vis.selectAll("g").data(graph.nodes).enter().append("g")
node = gnode.append("circle")
.attr("r", 8)
.attr('fill', '#fc434b')
.attr('id', 'node')
如果我写如下代码,问题解决了,但我需要添加 g
以便稍后向每个节点添加文本。
gnode = vis.selectAll("circle").data(graph.nodes).enter().append("circle")
node = gnode.attr("r", 8)
.attr('fill', '#fc434b')
.attr('id', 'node')
答案 0 :(得分:-1)
首先,不要使用 V3,它已经过时了。使用 V5 或更高版本。
D3 进入/退出模式的常见情况是:
selectAll(...).data(items, item => item.id).enter()
,其中data()的第二个参数指定了渲染对象的识别方式。所以,你的数据应该是这样的:
[
{id: 1, ...},
{id: 2, ...},
...
{id: N, ...}
]
,其中 id 属性在输入的对象范围内唯一
检查您的数据 (graph.nodes) 是否有效。