Javascript 不';t更新每个函数中的d3.js元素
我的代码运行正常,它向我显示了数据的元素,但在更改数据并再次运行相同的代码后,d3不会更新SVG元素的文本。我必须刷新整个网站,它才能改变Javascript 不';t更新每个函数中的d3.js元素,javascript,d3.js,each,Javascript,D3.js,Each,我的代码运行正常,它向我显示了数据的元素,但在更改数据并再次运行相同的代码后,d3不会更新SVG元素的文本。我必须刷新整个网站,它才能改变 var blackbox= d3.select("#content") .selectAll(".silencer") .data([0]); blackbox.enter()
var blackbox= d3.select("#content")
.selectAll(".silencer")
.data([0]);
blackbox.enter()
.append("div")
.attr("class", "silencer")
.attr("id", "silencer");
blackbox.exit().remove();
var box = blackbox.selectAll(".ursa")
.data(fraung);
box.enter()
.append("div")
.attr("class", "ursa")
.each(function(d) {
d3.select(this)
.append("svg")
.attr("class", "invoker")
.each(function(d) {
d3.select(this).append("svg:image")
.attr("xlink:href", "images/qwer.png")
.attr("x", "0")
.attr("y", "0")
.attr("width", "100")
.attr("height", "100")
.append("title")
.text(function(d) {return (d.name)});
});
d3.select(this).append("div")
.attr("class", "chen")
.each(function(d) {
d3.select(this).append("table")
.attr("class", "tab")
.each(function(d) {
d3.select(this).append("tbody")
.each(function(d) {
d3.select(this).append("tr")
.text(function(d) {return("Name: ")})
.attr("class", "key")
.each(function(d) {
d3.select(this).append("td")
.text(function(d) {return (d.name)});
});
});
});
});
});
box.exit().remove();
听起来,在加载第二个数据集之前,SVG元素没有被清除,因此第二个数据集被绘制在第一个数据集之后。如果唯一正在改变的是文本,那么看起来什么都没有发生。浏览器刷新将清除任何动态绘制的内容。在调用“blackbox”之前,您可以执行类似的操作来清除“#content”元素中的所有内容,我假设它是您的SVG容器
if(!d3.select("#content").empty()) d3.select("#content").remove();
这将完全删除SVG容器。因此,在加载新数据之前,您必须再次创建它。或者,如果您只想从SVG容器中删除子元素,可以执行以下操作:
if(!d3.select("#content").selectAll("*").empty()) d3.select("#content").selectAll("*").remove();
这可能会奏效,但我不想一次又一次地删除和创建它们。必须有另一种方法。如果您再次运行相同的代码,它将执行所有代码,而不仅仅是控制文本元素的部分,我猜这就是现在正在发生的事情,因此您描述的问题。如果只想更改文本,可以检查内容是否已经存在,然后选择先前存在的文本并进行更改,而不是运行发布的所有代码块。