D3如何更新文字?

时间:2015-10-02 00:56:37

标签: javascript html 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;
              });
});

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

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

1 个答案:

答案 0 :(得分:3)

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

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

修改了jsbin here