问题
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