2013-04-30 99 views
0

我有在底部有幾個SVG文本元素這樣的:D3選擇SVG文本元素

<svg width="750" height="3860"><g transform="translate(10,30)"> 
<rect class="bar negative Tuvalu" x="29.51594399999999" y="0" width="528.934056" country="Tuvalu" height="20" style="stroke: #ffffff;"></rect> 
... 
<text class="recipient Somalia unselected_text" y="40" x="558.45" style="font-size: 14px;" country="Somalia" dx="3" dy="-0.45em">Somalia -79.7545</text> 
<text class="recipient Tuvalu" y="20" x="558.45" style="font-size: 14px;" country="Tuvalu" dx="3" dy="-0.45em">Tuvalu -85.2432</text> 
... 

我想用這個地方COUNTRYNAME是一個類名來只選擇欄中的文本元素:

var className = "text." + countryname 
var textNode = d3.select("#barchart").select(className) 

但我在Chrome中得到的結果是1的數組,其中0的位置爲空。如果我只是選擇「。{countryname}」,它可以工作,但我只想指定文本節點。第一種方法實際上在我的一個圖中起作用,但是當我使用不同的數據創建新圖時,它不起作用。

+0

沒有添加不同的數據,例如新的圖形,當你改變任何東西更改圖表的ID? – 2013-04-30 10:05:51

回答

1

我轉載了您的簡化代碼,並且按預期工作。所以你將不得不向我們展示更多。

<div id="barchart"> 
<svg width="750" height="3860"> 
    <g transform="translate(10,30)"> 
    <rect class="bar negative Tuvalu" x="29.51594399999999" y="0" width="528.934056" country="Tuvalu" height="20" style="stroke: #ffffff;"></rect> 
    <text class="recipient Somalia unselected_text" y="40" x="558.45" style="font-size: 14px;" country="Somalia" dx="3" dy="-0.45em">Somalia -79.7545</text> 
    <text class="recipient Tuvalu" y="20" x="558.45" style="font-size: 14px;" country="Tuvalu" dx="3" dy="-0.45em">Tuvalu -85.2432</text> 
    </g> 
</svg> 
</div> 

<script type="text/javascript"> 
    var countryname = 'Somalia'; 
    var className = "text." + countryname; 
    var textNode = d3.select("#barchart").select(className); 
    console.log(textNode); 
</script> 

順便說一句,你還可以過濾選擇的類名設置,如果你需要更多的控制:

var textNode = d3.select("#barchart").selectAll("svg text").filter(function(d, i){ return this.classList.contains(countryname); });