简体   繁体   中英

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. 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 ). 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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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