Javascript 为什么标签没有添加到我的所有路径中?

Javascript 为什么标签没有添加到我的所有路径中?,javascript,d3.js,Javascript,D3.js,普朗克: 为什么下面没有为我的所有多边形添加“测试”标签 /* NOT Working code */ groups.selectAll('.path_placeholder') .enter() .append('text') .text("test") 更新 .enter()不是Xavier提到的必需项。删除它会显示所有节点的“测试”。但是,当我提供数据并按如下方式使用enter()时,为什么它不起作用呢 groups.selectAll('.path_placeho

普朗克:

为什么下面没有为我的所有多边形添加“测试”标签

 /* NOT Working code */
 groups.selectAll('.path_placeholder')
   .enter()
   .append('text')
   .text("test")
更新

.enter()不是Xavier提到的必需项。删除它会显示所有节点的“测试”。但是,当我提供数据并按如下方式使用enter()时,为什么它不起作用呢

groups.selectAll('.path_placeholder')
    .data(groupIds, function(d) { 
      return d; 
      })
    .enter()
    .append('text')
    .text(function(d){
      console.log(d);
      return d;
    })

我正在尝试为我的每个多边形显示标签,现在只是尝试为每个多边形添加一个虚拟标签

这里的问题是
路径
选择,而不是
选择:

paths = groups.selectAll('.path_placeholder')
    .data(groupIds, function(d) { return +d; })
    .enter()
    .append('g')
    .attr('class', 'path_placeholder')
    .append('path')//this makes the selection pointing to <path> elements
    .attr('stroke', function(d) { return color(d); })
    .attr('fill', function(d) { return color(d); })
    .attr('opacity', 0);
。。。您的“输入”选择为空,因为您已经有了与该
路径关联的数据

除此之外,对文本使用适当的“输入”选择没有什么意义,因为数据是绑定到组的相同数据

解决方案:这里的解决方案是针对这种情况的惯用D3,它创建了一个实际的
选择

我们可以通过断开
路径
选择,并为其命名:

pathGroups = groups.selectAll('.path_placeholder')
    .data(groupIds, function(d) {
        return +d;
    })
    .enter()
    .append('g')
    .attr('class', 'path_placeholder');
然后你可以做:

paths = pathGroups.append('path')
    .attr('stroke', function(d) {
        return color(d);
    })
    .attr('fill', function(d) {
        return color(d);
    })
    .attr('opacity', 0)

texts = pathGroups.append('text')
    .text(function(d) {
        return d;
    });

这是一个分叉的插件:

只需删除
enter()
,因为您不提供
数据
组。选择all('.path\u占位符')。追加('text')。文本(“test”)
谢谢您的帮助。如果我确实使用``groups.selectAll('.path_placeholder').data(groupIds,函数(d){return d;}.enter().append('text').text(函数(d){console.log(d);return d;})``提供数据会怎么样。更新了问题。
paths = pathGroups.append('path')
    .attr('stroke', function(d) {
        return color(d);
    })
    .attr('fill', function(d) {
        return color(d);
    })
    .attr('opacity', 0)

texts = pathGroups.append('text')
    .text(function(d) {
        return d;
    });