简体   繁体   中英

D3, having trouble adding new group element and line

I'm in the process of visualizing a linked list. Just doing it for fun and to learn d3.js. I am able to create group elements for the circles (which represent a node). But I can't figure out why a new group element is not being added after that. I want this new group to contain the line/arrow (the .next reference representation). I debugged through CDT the code is being executed but nothing is being added to the DOM.

var g = svg.selectAll("g")
        .data(dataArr)
    .enter().append("g")
        .attr("transform", function() {
            if (addMethod === "headAdd") {
                return "translate(" + 50 + " ," + y + ")";
            } else {
                return "translate(" + x + " ," + y + ")";
            }
        })
        .attr("class", "nodes")
        .attr("id", function(d) { return d.getData(); });

    // Create a circle representing the node.
    g.append("circle")
        .attr("r", 40)
        .style("fill", "#7DC24B")
        .style("stroke", "#122A0A")
        .style("stroke-width", 5)
        .style("opacity", 0)
        .style("stroke-opacity", 0.8)
        .transition().duration(1000).style("opacity", 1);

    // Add data to the node.
    g.append("text")
        .attr("dy", ".35em")
        .attr("text-anchor", "middle")
        .style("fill", "#ffffff")
        .text(function(d) { return d.getData(); });


    // Create the "next" arrow.
    // l is the line group that will enclose the line
    // and the text.

    // This doesn't seem to be working from here below.
    var l = svg.selectAll("g")
        .data(["1"])
    .enter().append("g")
        .attr("class", "lines")
        .attr("transform", "translate(" + (x + 40) + ", " + y + ")");

    l.append("line")
        .attr("x1", x + 40)
        .attr("y1", y)
        .attr("x2", x + 100)
        .attr("y2", y)
        .style("stroke", "#8EBD99")
        .style("stroke-width", 30); 

The ...

var l = svg.selectAll("g")
        .data(["1"])

... selects the existing group elements (ie the one you've just created) and performs a data join with those. The enter() selection will be empty since the elements you selected were already present in the DOM. Therefore the parts after .enter() will not be executed and the l selection will be empty.

You have to make the selector more specific, like:

var l = svg.selectAll(".lines")
        .data(["1"])

The Thinking with Joins article does a good job in explaining the data join concepts. See also the General Update Patterns (I,II,III) for more details about the different kind of selections you'll encounter during data joins.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM