问题
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