假设我们有一个没有子节点的 svg 元素:
<svg id="bargraph" width="400" height="90" ></svg>
Run Code Online (Sandbox Code Playgroud)
假设我们还有一个数据数组:
var data = [10,20,30,40,50];
Run Code Online (Sandbox Code Playgroud)
此代码正确地将新的 rect 元素附加到 svg 元素。
d3.select("#bargraph")
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.attr("height", 10)
.attr("width", function(d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) { return i * 20; })
.attr("fill", "blue");
Run Code Online (Sandbox Code Playgroud)
下面的代码不会将新的 rect 元素附加到 svg 元素。你能告诉我为什么吗?
d3.selectAll("#bargraph rect")
.data(data)
.enter()
.append("rect")
.attr("height", 10)
.attr("width", function(d) { return d; })
.attr("x", 0)
.attr("y", function (d, i) { return i * 20; })
.attr("fill", "blue");
Run Code Online (Sandbox Code Playgroud)