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

前端 未结 1 625
长情又很酷
长情又很酷 2021-01-03 08:32

I have this reusable pattern to create a table, inspired by http://bl.ocks.org/3687826, and I have two questions about it.

This is the function:

d3.t         


        
相关标签:
1条回答
  • 2021-01-03 09:26

    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!

    0 讨论(0)
提交回复
热议问题