javascript 删除 d3 svg 元素以进行重绘

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/22382984/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 23:02:11  来源:igfitidea点击:

Deleting d3 svg elements for redraw

javascripthtmlxmlsvgd3.js

提问by Mkni1408

I hope you can help me, because this is driving me nuts!

我希望你能帮助我,因为这让我发疯!

So i was trying to redraw a svg using d3. In my code i add the svg using:

所以我试图使用 d3 重绘一个 svg。在我的代码中,我使用以下方法添加 svg:

d3.xml("Images/vertical_line.svg", "image/svg+xml", function(xml) {

  var importedNode = document.importNode(xml.documentElement, true);
  var svg = d3.select('#'+id+'_verticallinecontainer').node().appendChild(importedNode);

  });

When my update function is called i then proceed to remove the element:

当我的更新函数被调用时,我将继续删除元素:

d3.select("#"+id+'_verticallinecontainer').remove();

This removes the container and the element. I then proceed with redrawing the svg again using the above code.

这将删除容器和元素。然后我继续使用上面的代码重新绘制 svg。

My problem is that when it appends the svg again it does it twice and i do not understand why! It seems that d3 somehow caches the svg, adding it again.

我的问题是,当它再次附加 svg 时,它会重复两次,我不明白为什么!似乎 d3 以某种方式缓存了 svg,再次添加它。

Hope you can help to clear out what is wrong, any help would be appreciated!

希望您能帮助解决问题,任何帮助将不胜感激!

回答by FernOfTheAndes

FIDDLEwith a quick example of adding, removing and the adding again an SVG and a contained circle. Hope this helps.

FIDDLE提供添加、删除和再次添加 SVG 和包含的圆的快速示例。希望这可以帮助。

function update() {
    svg.remove();
    svg = d3.selectAll("body").append("svg");
    svg.append("circle")
        .attr("cx",40)
        .attr("cy",40)
        .attr("r",20)
        .style("fill","blue");
}

回答by KateJean

I had a similar problem to this. removing the SVG element did not allow me to fully update the data like I wanted.

我有一个类似的问题。删除 SVG 元素不允许我像我想要的那样完全更新数据。

Instead, I removed the g elements created inside the SVG with this line:

相反,我使用以下行删除了在 SVG 内创建的 g 元素:

d3.selectAll("g > *").remove()

in my updateGraph() function

在我的 updateGraph() 函数中

Full explanation and situation shown here: Repainting/Refreshing Graph in D3

此处显示的完整说明和情况: D3 中的重新绘制/刷新图