2015-06-23 14 views
2

比方說,我得到這個代碼衰落中的節點:D3節點更新 - 如何在多個節點中選擇特定的文本元素?

var nodeEnter = node.enter().append("g") 
    .attr("class", "node") 
    .attr("transform", function (d) { 
    return "translate(" + d.x + "," + d.y + ")"; 
}) 
    .on("click", collapse); 

nodeEnter.append("rect") 
    .attr("class", "rect") 
    .attr("width", 170) 
    .attr("height", 80) 
    .attr("x", -85) 
    .attr("y", -80) 
    .attr("opacity", 0) 
    .style("fill", "#989898") 
    .style("stroke", "#65737e"); 

nodeEnter.append("text") 
    .attr("class", "title") 
    .attr("x", -80) 
    .attr("y", -70) 
    .attr("opacity", 0) 
    .attr("fill", "black") 
    .attr("dy", ".71em") 
    .text(function (d) { 
    return d.title; 
}); 

nodeEnter.append("text") 
    .attr("class", "name") 
    .attr("x", -80) 
    .attr("y", -70) 
    .attr("opacity", 0) 
    .attr("fill", "black") 
    .attr("dy", "1.86em") 
    .text(function (d) { 
    return d.firstName + " " + d.lastName; 
}); 

而且會像這樣被更新:

var nodeUpdate = node.transition() 
    .duration(duration) 
    .attr("transform", function (d) { 
    return "translate(" + d.x + "," + d.y + ")"; 
}); 

nodeUpdate.select("rect") 
    .attr("width", 170) 
    .attr("height", 80) 
    .attr("x", -85) 
    .attr("y", -80) 
    .attr("opacity", 1) 
    .style("fill", "#989898") 
    .style("stroke", "#65737e"); 

nodeUpdate.select("text") 
    .attr("class", "title") 
    .attr("x", -80) 
    .attr("y", -70) 
    .attr("opacity", 1) 
    .attr("fill", "black") 
    .attr("dy", ".71em") 
    .text(function (d) { 
    return d.title; 
}); 

nodeUpdate.select("text") 
    .attr("class", "name") 
    .attr("x", -80) 
    .attr("y", -70) 
    .attr("opacity", 1) 
    .attr("fill", "black") 
    .attr("dy", "1.86em") 
    .text(function (d) { 
    return d.firstName + " " + d.lastName; 
}); 

我的問題是,現在我追加多個文本元素(標題和名字)一個節點,但只顯示最後一個,因爲其他的似乎被覆蓋,因爲我沒有選擇特定的文本元素。我嘗試在追加時保存變量中的每個元素,以及按類選擇它們,但這些選項都不起作用。有沒有人有這個解決方案?

+0

你可能想'。選擇(「text.title」)'和'.select(「text.name」)'。 –

+0

作品!非常感謝你。 – StrikeAgainst

回答

1

問題是你有多個text元素需要單獨處理,但是你在選擇器中沒有區分它們。你可以做到這一點很容易使用,你已經分配給他們的班,即代替

.select("text") 

你會做

.select("text.title") 

.select("text.name") 
相關問題