How to remove D3 link text from visualization

不羁岁月 提交于 2021-01-28 04:03:26

问题


When nodes within my force directed visualization are clicked any child nodes (and their associated links) are toggled on/off. However, the text which acts as a label for these links is not removed when its associated child node and link are removed. See below:

Here is the relevant section of code, with the last line (linkText.exit.remove()) being my attempt at removing these labels:

var nodes = flatten(data);
var links = d3.layout.tree().links(nodes);

var path = vis.selectAll('path.link')
  .data(links, function(d) {
    return d.target.id;
  });

path.enter().insert('svg:path')
  .attr({
    class: 'link',
    id: function(d) {
      return 'text-path-' + d.target.id;
    },
    'marker-end': 'url(#end)'
  })
  .style('stroke', '#ccc');

var linkText = vis.selectAll('g.link-text').data(links);

linkText.enter()
  .append('text')
    .append('textPath')
      .attr('xlink:href', function(d) {
        return '#text-path-' + d.target.id;
      })
      .style('text-anchor', 'middle')
      .attr('startOffset', '50%')
      .text(function(d) {return d.target.customer_id});

path.exit().remove();

linkText.exit().remove();

Here is a link to a block as well: http://blockbuilder.org/MattDionis/5f966a5230079d9eb9f4


回答1:


It turns out no g element with class link-text ever gets created, so the exit selection is empty.

Replace

linkText.enter()
    .append('text')
        .append('textPath')
        .attr('xlink:href', function(d) {
            return '#text-path-' + d.target.id;
        });

with

linkText.enter()
    .append('g')
    .attr('class', 'link-text')
        .append('text')
            .append('textPath')
            .attr('xlink:href', function(d) {
                return '#text-path-' + d.target.id;
            });

Also, it's necessary to specify the identifier function for linkText just like you did for path, otherwise d3 cannot match the missing data with an exit selection!

var linkText = vis.selectAll('g.link-text').data(
    links,
    function (d) { return d.target.id; }
);


来源:https://stackoverflow.com/questions/34142410/how-to-remove-d3-link-text-from-visualization

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!