我在底部有几个像这样的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>
...
我试图通过bar选择文本元素,其中countryname是一个类名:
var className = "text." + countryname
var textNode = d3.select("#barchart").select(className)
但我在Chrome中获得的结果是1的数组,其中0位置为空。如果我只选择“。{countryname}”,它可以工作,但我只想指定文本节点。第一种方式实际上在我的一个图中工作,但是当我创建一个包含不同数据的新图时,它不起作用。
答案 0 :(得分: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); });