D3如何更新文字?

use*_*865 6 html javascript d3.js

我创建了具有一定价值的文本节点。因此,每当数据更新时,只应更新值,不应再次创建文本节点。

systemLevel
.enter()
.append('g')
.classed("system-level", true)
.attr("depth", function(d, i) {
  return i;
})
.each(function(d, i) {
  var columnHeader = graphHeaders.append("g")
                                 .classed("system-column-header", true);
  columnHeader.append('text')
              .attr('font-size', '14')
              .attr('font-weight', 'bold')
              .attr('fill', "red")
              .attr('x', 50 * i)
              .attr('y', 50)
              .text(function() {
                return d.newUser;
              });
  columnHeader.append('text')
              .attr('font-size', '14')
              .attr('font-weight', 'bold')
              .attr('fill', "blue")
              .attr('x', 50* i)
              .attr('y', 70)
              .text(function() {
                return d.value;
              });
});
Run Code Online (Sandbox Code Playgroud)

我在 Js Bin 上创建了一个例子。 https://jsbin.com/dixeqe/edit?js,output

我不确定,如何只更新文本值。任何帮助表示赞赏!

Lar*_*off 6

您没有使用通常的 D3 更新模式,这在许多教程中都有描述(例如这里)。您需要重构代码以使用它而不是无条件地附加新元素:

var columnHeader = graphHeaders.selectAll("g").data(dataset);
columnHeader.enter().append("g").classed("system-column-header", true);
var texts = columnHeader.selectAll("text").data(function(d) { return [d.newUser, d.value]; });
texts.enter().append("text")
  .attr('font-size', '14')
  .attr('font-weight', 'bold')
  .attr('fill', "red")
  .attr('x', function(d, i, j) { return 50 * j; })
  .attr('y', function(d, i) { return 50 + 20 * i; });
texts.text(function(d) { return d; });
Run Code Online (Sandbox Code Playgroud)

这里修改了jsbin 。