Javascript 在文本后面添加大小正确的矩形

Javascript 在文本后面添加大小正确的矩形,javascript,d3.js,Javascript,D3.js,我目前正在将文本节点添加到SVG,如下所示: var node = svg.selectAll(...); node.append("text") .attr("dy", 10) .attr("dx", 4) .text(function (d) { return d["name"]; }); 目前大约有10个节点,每个节点都有一个名称 我想在每个文本节点下方添加一个矩形,使用正确的宽度,我尝试了以下方法: node.select<SVGTSpanElement&

我目前正在将文本节点添加到SVG,如下所示:

var node = svg.selectAll(...);
node.append("text")
    .attr("dy", 10)
    .attr("dx", 4)
    .text(function (d) { return d["name"]; });
目前大约有10个节点,每个节点都有一个名称

我想在每个文本节点下方添加一个矩形,使用正确的宽度,我尝试了以下方法:

node.select<SVGTSpanElement>("text")
    .each(function(x, i) {
        console.log(this.getComputedTextLength());
        node.append("rect")
            .attr("fill", "#cccccc05")
            .attr("width", this.getComputedTextLength())
            .attr("height", 20)
    });
节点。选择(“文本”)
.每个(函数(x,i){
log(this.getComputedTextLength());
node.append(“rect”)
.attr(“填充”、“中交05”)
.attr(“宽度”,this.getComputedTextLength())
.attr(“高度”,20)
});
我的问题是(有点明显)我为每个节点创建了10个矩形,而不是每个节点一个


如何包含文本宽度的计算,并为每个文本元素添加一个矩形?

在不太重构代码的情况下,只需更改矩形的附加位置即可。在这种情况下,文本本身的父节点:

node.select<SVGTSpanElement>("text")
    .each(function(x, i) {
        console.log(this.getComputedTextLength());
        d3.select(this.parentNode).append("rect")
            .attr("fill", "#cccccc05")
            .attr("width", this.getComputedTextLength())
            .attr("height", 20)
    });
node.each(function(x, i) {
    d3.select(this).append("rect")
        .attr("fill", "#cccccc05")
        .attr("width", d3.select(this).select("text").node().getComputedTextLength())
        .attr("height", 20)
    });