javascript - D3,添加新组元素和行时遇到问题

标签 javascript svg d3.js

我正在可视化一个链接列表。只是为了好玩和学习 d3.js。我能够为圆圈创建组元素(代表一个节点)。但我不明白为什么此后没有添加新的组元素。我希望这个新组包含线/箭头(.next 引用表示)。我通过 CDT 调试代码正在执行,但没有任何内容添加到 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); 

最佳答案

...

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

...选择现有的组元素(即您刚刚创建的元素)并与这些元素执行数据连接。 Enter() 选择将为空,因为您选择的元素已经存在于 DOM 中。因此.enter()之后的部分将不会被执行,并且l选择将为空。

您必须使选择器更加具体,例如:

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

Thinking with Joins文章很好地解释了数据连接概念。另请参阅General Update Patterns (I,II,III)有关数据连接期间会遇到的不同类型选择的更多详细信息。

关于javascript - D3,添加新组元素和行时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14450244/

相关文章:

javascript - 如何在 Mobile Safari 中设置内容可编辑的 div 的文本插入位置?

javascript - 如何使 div 在该 div 中具有相同的图像大小?但整个网站上的所有图像仍然具有一致的尺寸?

html - 如何在客户端重写从服务器获取的 svg 文件?

javascript - d3 TreeMap 缩放仅在节点上

javascript - 如何在 Backbone.js 中处理简单的点击事件?

javascript - 当我单击元素外部时,如何删除添加到单击元素的功能?

javascript - 为什么我无法在 Jest 中导入 SVG?

css - SVG Rect 忽略高度?

javascript - d3.js 缩放仅在光标位于图形像素上时有效

javascript - 扩展 d3 树布局以在最终节点提供 HTML 框