我正在嘗試通過一些D3教程,所以請忍受我的noob問題。據我瞭解,爲了創建某種類型的新元素,您必須在不存在的元素上使用.selectAll()
,然後使用.append()
來創建它們。如果沒有現有的元素與指定的選擇器匹配,那麼這很有效,但如果存在,它將選擇那些元素並在其中添加新元素。就拿這個例子:使用selectAll()創建新元素,同時保留現有元素
d3.json("virusOrigins.json", function(dataset) {
var w = 200;
var h = 300;
var barPadding = 1;
var xScale = d3.scale.linear()
.domain([0, d3.max(dataset, function(d) { return d.value; })])
.rangeRound([5, w])
.nice();
var svg = d3.select("body")
.append("svg")
.attr("width", w)
.attr("height", h)
// append base rectangle
.append("rect")
.attr("width", w)
.attr("height", h)
.attr("fill", "#ccc");
svg.selectAll("rect.bars")
.data(dataset)
.enter()
.append("rect")
.attr("y", function(d, i) {
return i * (h/dataset.length);
})
.attr("x", 0)
.attr("width", function (d) {
return xScale(d.value);
})
.attr("height", function(d) {
return (h/dataset.length) - barPadding;
})
.attr("fill", "#f33")
.classed("bars", true);
});
這將導致以下HTML:
<svg width="200" height="300">
<rect width="200" height="300" fill="#ccc">
<rect y="0" x="0" width="13" height="32.333333333333336" fill="#f33" class="bars"></rect>
<rect y="33.333333333333336" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
<rect y="66.66666666666667" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
<rect y="100" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
<rect y="133.33333333333334" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
<rect y="166.66666666666669" x="0" width="200" height="32.333333333333336" fill="#f33" class="bars"></rect>
<rect y="200" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
<rect y="233.33333333333334" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
<rect y="266.6666666666667" x="0" width="5" height="32.333333333333336" fill="#f33" class="bars"></rect>
</rect>
</svg>
我怎樣才能動態創建矩形的底座矩形的是兄弟姐妹?
哦,我明白了。通過使用鏈接,初始矩形成爲該選擇的一部分。我認爲它會引用svg元素本身。 –