简体   繁体   中英

d3js elements not updated when data is updated

According to the document, a collection should update itself if the data is updated. For example, I have two elements in an array:

[{name: "Tom", age:10}, {name: "Prank", age:12}]

and this data is already joined to the following DOM elements

<div class="container">
  <div class="el">Tom is 10 yrs old</div>
  <div class="el">Prank is 12 yrs old</div>
</div>

and the data is updated.

[{name: "Tom", age:20}, {name: "Prank", age:22}]

I want the DOM to be

<div class="container">
  <div class="el">Tom is 20 yrs old</div>
  <div class="el">Prank is 22 yrs old</div>
</div>

but since the number of elements and the size of data is the same, the div elements do not seem to get updated. Am I missing something here? The above example is a simplified version of my code below, but I believe understanding how to update the above example correctly will solve the problem.

  function draw(data) {
    var bars = d3.select(".container")
      .selectAll(".bar-wrapper")
      .data(data);
    var barEnter = bars
      .enter()
      .append("div")
      .attr("class", "bar-wrapper")
    barEnter
      .append("button")
      .text(function(d) { return "Vote "+ d.name; })
      .attr("class", "vote-btn btn-default btn-primary")
      .on("click", function(d) {
        console.log("send Data", d.name);
        sendData(d.name);
      });
    barEnter
      .append("div")
      .attr("class", "bar")
      .style("width", function (d) {
        return (d.vote*10) + "px";
      })
      .text(function(d) { return d.vote });
    bars
      .exit()
      .remove()
  };

Any help will be appreciated!

The problem is that you're not handling the update selection, only the enter and exit selections. For the update selection, set the relevant attributes again:

bars.style("width", function (d) {
    return (d.vote*10) + "px";
  })
  .text(function(d) { return d.vote });

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