将基于 g 的 id 的文本附加到所选的 gs:无法读取未定义的属性"attr"



我的页面上有几个g,每个g都带有不同的ID。我想附加这些g一个显示此ID的文本。

这是我的代码:

    d3.selectAll("g")
        .append('text')
        .attr('x', 60)
        .attr('y', 90)
        .text(function(d) {return d.attr("id")})
        .attr("font-family", "sans-serif")
        .attr("font-size", "20px")
        .attr("fill", "blue");

它返回错误:

Uncaught TypeError: Cannot read property 'attr' of undefined
    at SVGTextElement.<anonymous>

在D3中,著名的第一个参数是指绑定到元素的 datum (因此,因此,相应的参数通常称为 d(。<<<<<<<<<<

您不想要基准。您想获得文本的父元素的<g>元素。因此,使用:

.text(function() {
    return d3.select(this.parentNode).attr("id")
});

这是一个演示:

d3.selectAll("g")
  .append('text')
  .attr('x', 60)
  .attr('y', (_, i) => 20 + i * 20)
  .text(function() {
    return d3.select(this.parentNode).attr("id")
  });
<script src="https://d3js.org/d3.v4.min.js"></script>
<svg>
  <g id="foo"></g>
  <g id="bar"></g>
  <g id="baz"></g>
</svg>