我正在可视化一个链接列表。只是为了好玩和学习 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/