How to update d3 table?

血红的双手。 提交于 2020-01-13 12:24:27

问题


I have some problem to update my d3.js table when mousemoving. Here is a simplified example in jsfiddle.

Here is the main code:

 function mousemove() {

  var newdata = [{Variable: "x", Value: 1}, {Variable: "y", Value: 1}]

  table.selectAll("tbody.tr")
    .data(newdata)
    .enter()
    .append("tr")
    .selectAll("td")
    .data(function(row) {
      return columns.map(function(column) {
        return {column: column, value: row[column]};
      });
    })
    .enter()
    .append("td")
    .text(function(d) { return d.value; });
};

namely, how can I only update the values in the table instead of drawing a new table again and again?

Thank you!


回答1:


Use your previously defined selections(in jsfiddle example)

var table = d3.select("body").append("table");
var tbody = table.append("tbody");

Using this selection, you can update the existing table. In your mouseover() function, you have used enter() as an attempt to update your table. But since enter() sees that required number of placeholders (2 placeholders for 2 rows) are already present, it will not do anything. You can update by removing enter() and append statements and doing something like:

tbody.selectAll("tr")
  .data(newdata)
  .selectAll("td")
  .data(function(row) {
    return columns.map(function(column) {
      return {
        column: column,
        value: row[column]
      };
    });
  })
  .text(function(d) {return d.value;});

Ideally you should follow the enter(), update() and exit() sequence for such d3 updates, but for this situation just the above changes will suffice.




回答2:


There is a great tutorial about update pattern at http://bl.ocks.org/mbostock/3808218.

Generally for updates You should have a key for data joins, passed as the second parameter in .data(values, key).

I've updated yours jsfiddle using enter, update, delete pattern for reference:

 var rows = table.selectAll("tbody tr")
.data(newdata, function (d) {return d.Variable;});

rows.enter()
.append('tr')
.selectAll("td")
.data(function (d) {return [d.Variable, d.Value];})
.enter()
.append("td")
.text(function(d) { return d; });

rows.exit().remove();

var cells = rows.selectAll('td')
.data(function (d) {return [d.Variable, d.Value];})
.text(function (d) {return d;});

cells.enter()
.append("td")
.text(function(d) { return d; });

cells.exit().remove();

https://jsfiddle.net/qL7knnkv/



来源:https://stackoverflow.com/questions/32871044/how-to-update-d3-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!