D3选择SVG文本元素

D3 Selecting SVG Text Elements

本文关键字:元素 文本 SVG 选择 D3      更新时间:2023-09-26

底部有几个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}",它可以工作,但我只想指定文本节点。第一种方法实际上在我的一个图中工作,但是当我用不同的数据创建一个新图时,它不起作用。

我复制了您的简化代码,并按预期工作。所以你得给我们展示更多。

<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); });