LinkText does not work in d3js tree structure

I am trying to put linkText for a link in a d3js tree structure, but this is not wlrking created by the jsfiddle project here . Can someone tell me why linkText is not suitable.

var link = svg.selectAll(".link")
                .data(links, function (d) {
                    return d.target.id;
            });
link.enter().insert("path", "g")
.attr("class", "link")
.attr("d", function (d) {
    var o = {
        x : source.x0,
        y : source.y0
    };
    return diagonal({
        source : o,
        target : o
    });
});

link.transition().duration(duration)
.style("stroke", function (d) {
    return "#99FFCC";
})
.attr("d", diagonal);
link.append("text")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("fill", "Black")
.style("font", "normal 12px Arial").attr("transform", function(d) {
    return "translate(" +
        (d.target.y - 50) + "," + 
        (d.target.x - 10) + ")";
}).attr("text-anchor", "middle").text(function (d) {
alert(d.target.label);
return d.target.label;
});
+4
source share
1 answer

Your mistake here:

link.enter().insert("path", "g")
.attr("class", "link")
...
...
link.append("text")
.attr("font-family", "Arial, Helvetica, sans-serif")
.attr("fill", "Black")

This code will put the text in the DOM path, which is incorrect. DOM text should never be inside the DOM path.

The correct code should be like this:

// Update the links…
    var link = svg.selectAll("path.link")
        .data(links);
    //adding the text to the svg
link.enter().insert("text")
        .attr("font-family", "Arial, Helvetica, sans-serif")
        .attr("fill", "Black")
        .style("font", "normal 12px Arial")
         .attr("transform", function (d) {
                return "translate(" + (d.target.y - 30) + "," + (d.target.x - 10) + ")";
            })
        .attr("text-anchor", "middle")
        .text(function (d) {
        console.log(d.target.label);
        return d.target.label;
    });

Full working code here .

+2
source

Source: https://habr.com/ru/post/1609297/


All Articles