我不知道如何最好地将发生在父节点(例如 SVGg
元素)的数据更改传递给它的子节点(例如 SVGcircle
元素)。
这是一个最小的工作示例。该示例假定您有一个名为的对象,该对象svg
引用包含 SVG 元素的 d3 选择。
data = [{"id":"A","name":"jim"},{"id":"B","name":"dave"},{"id":"C","name":"pete"}];
g = svg.selectAll("g").data(data, function(d) { return d.id; }).enter().append("g");
g.append("circle")
.attr("r", 3)
.attr("cx", 100)
.attr("cy", function(d,i) {return 100 + (i * 30);})
// The data gets passed down to the circles (I think):
console.log("circle data:");
d3.selectAll("g circle").each(function(d) { console.log(d.name); });
// Now change the data, and update the groups' data accordingly
data = [{"id":"A","name":"carol"},{"id":"B","name":"diane"},{"id":"C","name":"susan"}];
svg.selectAll("g").data(data, function(d) { return d.id;});
// These are the results of the change:
console.log("after change, the group has:");
d3.selectAll("g").each(function(d) { console.log(d.name); });
console.log("but the circles still have:");
d3.selectAll("g circle").each(function(d) { console.log(d.name); });
谁能帮我找到一种简洁的方法将新名称放入组的所有子元素中?在我的真实示例中,每个都g
包含许多circle
s。