【问题标题】:Can't remove Child element of node in D3.js Force-Directed Graph无法在 D3.js Force-Directed Graph 中删除节点的子元素
【发布时间】:2013-05-16 14:19:51
【问题描述】:

我正在使用 D3.js Force-Directed Graph 就像这个 Demo here。例如,我修改了此代码,用 SVG 图像和标签更改圆圈并与 SVG 路径链接。单击节点它是展开和折叠子节点,意味着在节点的鼠标单击时添加和删除子节点。

添加新节点后,所有现有节点也重新创建图像和标签,旧节点仍然存在,但我想只更新新节点而不影响现有节点。

与删除节点相同的问题应该用新节点替换旧节点,不将新元素附加到节点不影响其他现有节点,仅更改添加或删除的节点。

function update() {
    var nodes = flatten(root),
        links = d3.layout.tree().links(nodes);

    // Restart the force layout.
    force.nodes(nodes)
        .links(links)
        .linkDistance(120)
        .charge(-500)
        .start();

    path = vis.selectAll("path.link");
    path = path.data(force.links());
    path.enter().append("svg:path")
        .attr("class", "link")
        .attr("marker-end", "url(#end)");

    path.exit().remove();
    node = vis.selectAll(".node");
    node = node.data(force.nodes());
    node.enter().append("g")
        .attr("class", "node")
        .on("click", click)
        .call(force.drag);

    node.append("image")
        .attr("xlink:href", function (d) {
        return "http://t2.gstatic.com/images?q=tbn:ANd9GcT6fN48PEP2-z-JbutdhqfypsYdciYTAZEziHpBJZLAfM6rxqYX";
    })
        .attr("class", "image")
        .attr("x", -15)
        .attr("y", -15)
        .attr("width", 24)
        .attr("height", 24);

    node.append("text")
        .attr("class", "text")
        .attr("x", 40)
        .attr("dy", ".35em")
        .style("fill", color)
        .text(function (d) {
        return d.name;
    });

    node.exit().remove();
}

我用我的代码 here 创建了一个小提琴。

【问题讨论】:

  • 这里我知道如何删除旧节点和链接 vis.selectAll(".node").remove();和 vis.selectAll("path.link").remove();删除旧路径和节点,但在节点上绘制路径,所以现在更新时 svg 非常糟糕,任何人都可以帮我更新链接,因为删除节点工作正常,但是当我尝试删除添加新路径的路径时创建节点.. :(

标签: javascript d3.js


【解决方案1】:

需要删除节点而不是其中的div,只需在force.start()之前添加两行

vis.selectAll("path").remove();
vis.selectAll(".node").remove();

fiddle的更新版本

【讨论】:

    猜你喜欢
    • 2015-03-18
    • 1970-01-01
    • 2017-06-18
    • 2017-10-10
    • 2013-03-20
    • 1970-01-01
    • 1970-01-01
    • 2011-11-10
    • 2012-01-28
    相关资源
    最近更新 更多