4
我正在與D3.js合作,並正在學習general update pattern。我知道它的簡單數據結構(我想!),但我想創建一個嵌套的DOM元素集:包含路徑和文本元素的組。我不清楚如何訪問嵌套的元素的更新/輸入/退出選擇。D3.js:如何遵循一般更新模式來轉換嵌套元素?
總之,這是我想結束了SVG結構:
<g class="team">
<path class="outer" d="..."></path>
<text class="legend" x="890" dy=".2em" y="23">Red Sox</text>
</g>
<g class="team">
<path class="outer" d="..."></path>
<text class="legend" x="890" dy=".2em" y="23">Yankees</text>
</g>
而且我希望能夠明確地訪問更新/輸入/選擇選擇每個元素。我的數據是這樣的:
[
{ "name": "Red Sox", "code": "RED", "results": [...] },
{ "name": "Yankees", "code": "YAN", "results": [...] },
]
這是我的代碼 - 看到它在全在的jsfiddle:http://jsfiddle.net/e2vdt/6/
function update(data) {
// Trying to follow the general update pattern:
// http://bl.ocks.org/mbostock/3808234
// Join new data with old elements, if any.
var g = vis.selectAll("g.team").data(data, function(d) {
return d.code;
});
// Update old elements as needed.
// QUESTION: How to get the update selection for the text elements?
// Currently the text element is not moving to the right position.
g.selectAll("text.legend").transition()
.duration(750)
.attr("y", function(d, i) { return i * 32 + 100; });
// Create new elements as needed.
var gEnter = g.enter()
.append("g").attr("class","team");
gEnter.append("text").attr("class", "legend")
.attr("dy", ".35em")
.attr("y", function(d, i) { return i * 32 + 100; })
.attr("x", "20")
.style("fill-opacity", 1e-6)
.text(function(d) { return d.name; })
.transition()
.duration(750)
.style("fill-opacity", 1);
// TBA: Add path element as well.
// Remove old elements as needed.
g.exit()
.transition()
.duration(750)
.attr("y", "0")
.style("fill-opacity", 1e-6)
.remove();
}
的進入和退出的選擇都工作正常,但我不知道知道如何獲取更新選擇,以便我可以將文本標籤移動到正確的位置。 「Red Sox」條目應該沿着頁面向下移動,但事實並非如此。
謝謝!實際上,我明確地想要定位'text'元素而不是'g' - 這是因爲我想要定位'path'元素,一旦我找到了解決方法。我試過http://jsfiddle.net/e2vdt/11/ - 我只是不知道如何獲得這些文本元素的更新選擇。 – Richard 2013-04-30 10:27:30
啊,它的工作正如你所期望的那樣 - 除非你正在更新它..到底是在哪裏。看看如果你調整更新位置的計算方式會發生什麼:http://jsfiddle.net/e2vdt/14/(爲清晰起見添加了樣式) – minikomi 2013-04-30 23:36:04
你搖滾,謝謝! – Richard 2013-05-01 13:16:56