使用d3.js删除svg文本元素

Removing svg text elements with d3.js

本文关键字:文本 元素 svg 删除 d3 js 使用      更新时间:2024-06-09

我可以用一个平滑的小tween来更改文本的值,但每次我都清空一个svg并创建一个新的svg。这最终会用空的SVG加载DOM。我该如何摆脱它们?

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()

    }

您可以删除特定元素,执行d3.select("#idOfElement").remove()。这里不需要.exit(),因为没有数据被匹配和绑定。