Updating an HTML table in d3.js using a reusable chart

对着背影说爱祢 提交于 2019-11-30 15:58:06

The problem is with these three lines of code:

// Creating the table
var table = selection.append("table");
var thead = table.append("thead");
var tbody = table.append("tbody");

which always appends new table, thead, and tbody elements to your document. Here's how you can do this conditionally, only when these elements don't already exist (the example you cite creates its div.header element similarly):

selection.selectAll('table').data([0]).enter().append('table');
var table = selection.select('table');

table.selectAll('thead').data([0]).enter().append('thead');
var thead = table.select('thead');

table.selectAll('tbody').data([0]).enter().append('tbody');
var tbody = table.select('tbody');

The selectAll().data([0]).enter().append() pattern conditionally creates a single element if it isn't found. The cited example used data([true]) but any array with a single element will do.

To filter the nested data from within your function, change your call to data() and pass a filtered subset of the selection data like this:

var rows = tbody.selectAll('tr').data(tbody.data()[0].filter(function(d) { 
    return d.price > 1400; 
}));

Good luck!

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