javascript 使用 d3.js 删除 svg 文本元素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20477224/
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
Removing svg text elements with d3.js
提问by JonnyD
I can change the value of the text with a smooth little tween, but every time I am emptying one svg and creating a new one. This eventually loads the DOM up with empty SVGs. How can I get rid of them?
我可以使用平滑的小补间更改文本的值,但是每次我清空一个 svg 并创建一个新的时。这最终会用空的 SVG 加载 DOM。我怎样才能摆脱它们?
D3:
D3:
var vis = d3.select("#visualisation"),
commasFormatter = '$' + d3.format(",.0f"),
numVis = d3.select("#defecit"),
defTotal = d3.select("#defense");
function init () {
//Initialize mean text
numVis.append("text")
.attr("id", "meantext")
.attr("y", 40)
.attr("x", 118)
.style("font-size", "26px")
.style("font-family","Arial, Helvetica, sans-serif")
.style('font-weight', 'bold')
.style('text-color', '#525252');
defTotal.append("text")
.attr("id", "defense")
.attr("y", 0)
.attr("x", 0)
.style("font-size", "16px")
.style("font-family","Arial, Helvetica, sans-serif")
.style('font-weight', 'bold')
.style('text-color', '#525252');
d3.select("#meantext")
.transition()
.duration(500)
.ease('linear')
.tween("text", function() {
var i = d3.interpolate(this.textContent, dollars.value);
return function(t) {
this.textContent = '$' + d3.format(",")(Math.round(i(t)));
};
})
//Doing something like this didn't work - kept giving me an error that the object array had no exit function
d3.select("meantext").exit().remove()
}
回答by Lars Kotthoff
You can remove a specific element, do d3.select("#idOfElement").remove()
. There's no need for .exit()
here as no data is being matched and bound.
您可以删除特定元素,请执行d3.select("#idOfElement").remove()
. 这里不需要,.exit()
因为没有数据被匹配和绑定。