简体   繁体   English

D3如何更新文字?

[英]D3 how to update text?

I have created text nodes that has some value. 我创建了具有一定价值的文本节点。 So whenever data updates, only the value should update, the text nodes shouldn't be created again. 因此,每当数据更新时,只应更新值,不应再次创建文本节点。

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

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

I am not sure, how to update just the text value. 我不确定,如何只更新文本值。 Any help is appreciated! 任何帮助表示赞赏!

You're not using the usual D3 update pattern, described in many tutorials (eg here ). 您没有使用许多教程中描述的常用D3更新模式(例如此处 )。 You need to restructure the code to use this instead of unconditionally appending new elements: 您需要重新构建代码以使用它而不是无条件地追加新元素:

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

Modified jsbin here . 在这里修改了jsbin。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM