0

我无法更新 DOM 中子节点上的数据属性。我正在使用 SVG 并将数据数组绑定到父组 ('g') 元素。然后这些组包含一个圆圈和一些文本。当我第一次创建圆圈时,来自父“g”的数据会自动传入并绑定到圆圈。我无法弄清楚当我更新父“g”元素上的数据时如何更新子“圆”节点上的数据。

这是一个示例来解释我正在尝试做的事情:

var test = svg.selectAll("g").data([1,2,3,4]);
test.enter().append("g");
test.append("circle");

我现在有以下 DOM:

svg -> g (__data__ = 1) -> circle (__data__ = 1)
       g (__data__ = 2) -> circle (__data__ = 2)
       g (__data__ = 3) -> circle (__data__ = 3)
       g (__data__ = 4) -> circle (__data__ = 4)

现在我想映射新数据:

var test2 = svg.selectAll("g").data([9,8,7,6]);

这给出了以下 DOM:

svg -> g (__data__ = 9) -> circle (__data__ = 1)
       g (__data__ = 8) -> circle (__data__ = 2)
       g (__data__ = 7) -> circle (__data__ = 3)
       g (__data__ = 6) -> circle (__data__ = 4)

我不知道如何让子圆节点继承其父 g 元素的数据值。

我尝试过以下方法但没有成功:

test2.selectAll("circle").data(function(d) { return d; })

test2.selectAll("circle").data(function(d) { return this.parentNode.__data__; })

有没有人建议这是如何完成的?

4

1 回答 1

5

运算符除了.select()选择单个元素外,还将数据从当前元素传播到所选元素。如果每个g元素仅包含一个circle元素,则可以将其用于您的目的

test2.select("circle");

但是,如果有多个,这将不会那么好circle,因为您需要单独选择它们中的每一个。

于 2013-10-09T19:56:02.277 回答