文字更新D3中的元素-v5

时间:2019-02-26 20:47:39

标签: javascript html d3.js svg auto-update

我尝试在SVG中的文本矩形的正确位置进行更新,但是以某种方式,我得到了rect的正确更新,但没有得到正确的更新。 text。当我删除起点和终点之间的元素时。即使我为文本工作id,它也总是删除最后一个。我只有text遇到了问题。

这是我的代码:

function addLabelCountry(data) {
  var rect = svg.selectAll(".rect-label").data(data);
  var text = svg.selectAll(".text-label").data(data);

  rect.exit().remove();
  text.exit().remove();

  rect
    .attr("x", contentWidth - 15)
    .attr("y", (d, i) => (i + 1) * 15 + 25)
    .style("fill", d => color(d.country));

  rect
    .enter()
    .append("rect")
    .transition()
    .duration(1000)
    .attr("class", "rect-label")
    .attr("x", contentWidth - 15)
    .attr("y", (d, i) => (i + 1) * 15 + 25)
    .attr("width", 10)
    .attr("height", 10)
    .style("fill", d => color(d.country));

  text
    .enter()
    .append("text")
    .attr("class", "text-label")
    .attr("x", contentWidth)
    .attr("y", (d, i) => (i + 1) * 15 + 35)
    .text(d => d.country);

  text
    .append("text")
    .attr("x", contentWidth)
    .attr("y", (d, i) => (i + 1) * 15 + 35)
    .text(d => d.country);
}

0 个答案:

没有答案