You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

D3.js力导向图更新数据时重复/嵌套节点问题求助

问题:D3.js更新数据后旧节点未移除导致重复

当新数据传入我的D3服务时,新数据集已加载,但旧节点未被移除,导致父元素<g>内出现重复节点。我刚接触D3.js,已查阅大量资料,了解到可用selection.join()替代enter().append(),也知晓node.exit().remove()和node.merge(node)这类操作方法。

从DOM可见,新节点属性重复出现在<g class="node">元素中,未替换原有数据,造成内容重叠。

节点构建代码如下:

const zoomContainer = d3.select('svg g');

const node = zoomContainer.selectAll('g').data(nodes, function (d) {
  return d.id;
});

//zoomContainer.selectAll('.node').data(node).exit().remove();

const nodeEnter = node
  .join('g')
  .attr('class', 'node')
  .call(
    d3
      .drag()
      .on('start', (d) => this.dragended(d3, d, simulation))
      .on('drag', function dragged(d) {
        d.fx = d3.event.x;
        d.fy = d3.event.y;
      })
      .on('end', (d) => this.dragended(d3, d, simulation))
  );

nodeEnter
  .append('circle')
  .style('fill', '#fff')
  .style('cursor', 'pointer')
  .style('fill-opacity', '1')
  .style('stroke-opacity', '0.5')
  .attr('id', (d, i) => d.id)
  .attr('r', 28);

nodeEnter
  .append('image')
  .attr('xlink:href', 'https://github.com/favicon.ico')
  .attr('x', -15)
  .attr('y', -60)
  .attr('width', 16)
  .attr('class', 'image')
  .style('cursor', 'pointer')
  .attr('height', 16);

const nodeText = nodeEnter
  .data(nodes)
  .append('text')
  .style('text-anchor', 'middle')
  .style('cursor', 'pointer')
  .attr('dy', -3)
  .attr('y', -25)
  .attr('class', 'nodeText')
  .attr('id', 'nodeText');

nodeText
  .selectAll('tspan')
  .data((d, i) => d.label)
  .join('tspan')
  .attr('class', 'nodeTextTspan')
  .text((d) => d)
  .style('font-size', '12px')
  .attr('x', -10)
  .attr('dx', 10)
  .attr('dy', 15);

我可以强制清空图表,但希望利用selection.join()的对比更新功能,以及enter().append().exit()相关操作。希望有人能指出为何重复节点未被移除或合并。

更新:
使用enter().append('g')替代join('g')后,效果有所改善。提前执行zoomContainer.selectAll('.node').data(node).exit().remove()后,节点可更新,但需要点击两次更新按钮。若使用join('g'),节点仍会重复,且该移除语句无效。

内容的提问来源于stack exchange,提问作者Tom Rudge

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.02 09:30:50