SVG 不显示通过 d3 & jquery 添加的元素

SVG not displaying elements added via d3 & jquery

我有一个通过 d3 创建的折线图。对于每个数据点(svg circle 元素),我使用 d3 & jquery 附加一个兄弟元素。元素确实已正确创建和添加,但它们没有出现。如果我在 Chrome 开发工具中编辑 HTML 块,文本元素会突然出现 - 好像需要先刷新 SVG 对象才能显示我附加的元素。

这是我用来插入文本元素的代码:

        chart.selectAll('circle.dot').each(
            function(){
                var thisCircle = $(this);
                var myText = document.createElement('text')
                $(myText).attr("x", +800)
                $(myText).attr("y", +200);
                $(myText).attr("fill", "red");
                $(myText).attr("font-family", "verdana");
                $(myText).text("testing");
                $(myText).attr("style", "font-weight:bold;z-index:100");

                this.parentNode.insertBefore(myText, this.nextSibling);
            }
        )

有没有办法重绘或刷新 svg,或者更好的是,在我追加节点时让它更新?

这种 D3 和 jQuery 的混合不仅没有必要,而且会使事情悄无声息地失败。除此之外,还有一种惯用的 D3 方式来完成您在这里所做的事情。所以,我建议你重构所有这些代码。但是,请记住,在这里我只会回答您的主要问题 ("SVG not displaying elements"),仅此而已。对于你的次要问题("Is there a way to redraw or refresh the SVG?")我建议你post一个新问题,MCVE.

话虽如此,让我们看看发生了什么:

您的代码中的问题在于您正在使用 createElement。由于这是一个 SVG,你必须使用 createElementNS,其中:

Creates an element with the specified namespace URI and qualified name. (emphasis mine)

SVG 的有效名称空间 URI 是:http://www.w3.org/2000/svg

因此,应该是:

var myText = document.createElementNS("http://www.w3.org/2000/svg", "text")

这是一个简单的演示,仅进行了更改:

d3.selectAll('circle').each(
  function() {
    var thisCircle = $(this);
    var myText = document.createElementNS("http://www.w3.org/2000/svg", 'text')
    $(myText).attr("x", 10)
    $(myText).attr("y", 70);
    $(myText).attr("fill", "red");
    $(myText).attr("font-family", "verdana");
    $(myText).text("testing");
    $(myText).attr("style", "font-weight:bold;z-index:100");

    this.parentNode.insertBefore(myText, this.nextSibling);
  }
)
<script src="https://d3js.org/d3.v4.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<svg>
  <circle cx="50" cy="50" r="10" fill="teal"></circle>
  <circle cx="150" cy="50" r="10" fill="teal"></circle>
  <circle cx="250" cy="50" r="10" fill="teal"></circle>
</svg>