你好,有一个 D3 SVG 对象:
d3.select("#chart").append("svg")
.attr('id', 'chartId' + idx)
我向其附加矩形以创建条形图。
我希望能够在 DOM 中添加和删除它。
我可以通过以下方式轻松删除它:
d3.select('svg#chartId' + j).remove();
如何重新附加刚刚删除的整个 SVG 图表?
最佳答案
D3 不支持重新附加已删除的节点。
selection.remove()
并没有完全销毁节点,它的行为与 jQuery 的 detach()
方法非常相似。 (将 jQuery 与 SVG 元素结合使用永远不会有好下场)
好消息是,使用内置的 SVG DOM 很容易做到这一点。
// .remove() returns the detached node.
var el = d3.select('.selection').remove();
var nativeEl = el[0][0];
nativeEl.parentNode.appendChild(nativeEl);
通常显示和隐藏这些元素可能会更容易,但在渲染后重新排列元素顺序等情况下,这可能非常有用。
关于javascript - 如何将现有的 D3 SVG 图表添加回 DOM?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11682527/