Updating the table multiple times using D3 does not work

霸气de小男生 提交于 2021-02-05 08:51:20

问题


I have a page that need to load a new data and update it to an existing table element using d3. I am writing the following but didn't work:

  // completeTableData = [ {head1:va1, head2: val2}, {haed1: val4, head2: val5}, ... ]
  var tr = d3.select("tbody")
    .selectAll("tr")
    .data(completeTableData);   
  tr.exit().remove();                       // remove the previous data in the table
  tr.merge(tr.enter().append("tr"));

  var td = tr.selectAll("td")
    td.data(function(d, i) { 
      return Object.values(d);
    });  
  td.exit().remove();
  td.merge(td.enter().append("td"));

It looks like tr updates correctly but the td always reflects on the previous data and didn't get updated.


回答1:


Selections in D3 are immutable. Therefore, this:

tr.merge(tr.enter().append("tr"));

... won't change what tr is. Since you obviously want it to be the "update + enter" selections, you have to reassign it:

tr = tr.merge(tr.enter().append("tr"));

Finally, I'd advise naming the enter selection, so the whole thing would be:

var trEnter = tr.enter().append("tr");
tr = tr.merge(trEnter);


来源:https://stackoverflow.com/questions/61666422/updating-the-table-multiple-times-using-d3-does-not-work

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