如何进入嵌套元素?

How to enter nested element?

我有六个 parent 元素(6 次 "div"),我要附加三个 children,最后三个 parent 中的每一个。

d3.select("body").selectAll("div")
    .data(["one", "two", "three", "four", "five", "six"])
    .enter().append("div")
    .attr("class", "parent")
    .text(function (d) {
    return d;
});

d3.selectAll("div")
    .filter(function (d, i) {
    return i > 2 ? true : false;
})
    .append("div")
    .attr("class", "children")
    .text(function (d) {
    return "Name of child: " + d;
});

这导致以下输出:

one
two
three
four
Name of child: four
five
Name of child: five
six
Name of child: six

现在,我想根据数据更新 children。结果应该有 children 在三、四和五。

问题是在 DOM 的正确位置追加输入的 child 三个。例如。下面试试:

var newChildren = ["three", "four", "five"];

var updateSel = d3.selectAll(".children").data(newChildren, function (d) {
    return d;
});
updateSel.exit().remove();
updateSel.enter().append("div")
    .attr("class", "children")
    .text(function (d) {
    return "Name of child: " + d;
});

将在错误的位置输入 child 三个,因为 parent 未指定为 parent 节点。

one
two
three
four
Name of child: four
five
Name of child: five
six
Name of child: three

Here's the JSFiddle.

您的 updateSel 需要基于父节点,而不是子节点,因为您可能希望将子节点添加到父节点。

因此您的初始选择变为:

var updateSel = d3.selectAll(".parent").data(newChildren, function (d) {
    return d;
});

那么您的删除命令将必须删除子项而不是退出选择中的节点:

updateSel.exit().selectAll("*").remove();

最后,您的附加命令必须被过滤以仅应用于那些还没有子节点的节点:

updateSel.filter(function() {
    return d3.select(this).select(".children").empty();
}).append("div")
    .attr("class", "children")
    .text(function (d) {
    return "Name of child: " + d;
});