我有一段 JavaScript 代码,它创建(使用 D3.js)一个包含图表的 svg
元素。我想根据来自使用 AJAX 的网络服务的新数据更新图表,问题是每次单击更新按钮时,它都会生成一个新的 svg
,所以我想删除旧的或更新它内容。
以下是我在其中创建 svg
的 JavaScript 函数的片段:
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h);
如何删除旧的 svg
元素或至少替换其内容?
d3.select("svg").empty();
这是解决方案:
d3.select("svg").remove();
这是 D3.js 提供的 remove
函数。
如果你想摆脱所有的孩子,
svg.selectAll("*").remove();
将删除与 svg 关联的所有内容。
在附加 svg 元素时设置 id 属性也可以让 d3 稍后通过 id 选择此元素上的 remove() :
var svg = d3.select("theParentElement").append("svg")
.attr("id","the_SVG_ID")
.attr("width",...
...
d3.select("#the_SVG_ID").remove();
我有两张图表。
<div id="barChart"></div>
<div id="bubbleChart"></div>
这删除了所有图表。
d3.select("svg").remove();
这适用于删除现有的条形图,但之后我无法重新添加条形图
d3.select("#barChart").remove();
试过这个。它不仅让我删除了现有的条形图,还让我重新添加了一个新的条形图。
d3.select("#barChart").select("svg").remove();
var svg = d3.select('#barChart')
.append('svg')
.attr('width', width + margins.left + margins.right)
.attr('height', height + margins.top + margins.bottom)
.append('g')
.attr('transform', 'translate(' + margins.left + ',' + margins.top + ')');
不确定这是否是删除的正确方法,并在 d3 中重新添加图表。它在 Chrome 中工作,但尚未在 IE 中测试。
我正在使用 D3.js 使用 SVG,我遇到了同样的问题。
我使用此代码删除了以前的 svg,但 SVG 中的线性渐变没有出现在 IE 中
$("#container_div_id").html("");
然后我写了下面的代码来解决这个问题
$('container_div_id g').remove();
$('#container_div_id path').remove();
在这里,我将删除 SVG 中以前的 g 和路径,替换为新的。
将我的线性渐变保持在静态内容中的 SVG 标记内,然后调用上面的代码,这在 IE 中有效
您也可以只使用 jQuery 删除包含您的 svg 的 div 的内容。
$("#container_div_id").html("");
如果您使用的是 xhtml,您应该使用 append("svg:svg")
而不是 append("svg")
,以便 D3 使元素具有正确的“命名空间”。
我遵循 https://www.d3-graph-gallery.com/graph/line_basic.html 中的代码并获得了以下代码:
svg.append("path")
.datum(filteredData)
.attr("fill", "none")
.attr("stroke", "blue")
.attr("stroke-width", 1.5)
.attr("d", d3.line()
.x(function(k) { return x(k.date) })
.y(function(k) { return y(k.value) })
)
所以对我来说,事实证明我在新线的产生之前就打了这个耳光:
d3.selectAll("path").remove()
不定期副业成功案例分享
svg.selectAll("*").remove();
。即使将svg
变量设置为分组元素 (g
),也会清除元素的内容。