使用可重复使用的图表中d3.js更新的HTML表(Updating an HTML table in

2019-07-18 16:57发布

我有这个可重用的模式创建一个表,灵感http://bl.ocks.org/3687826 ,我对此有两个问题。

这是函数:

d3.table = function(config) {
var columns = [];

var tbl = function(selection) {
if (columns.length == 0) columns = d3.keys(selection.data()[0][0]);
console.log(columns)    

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

// appending the header row
var th = thead.selectAll("th")
        .data(columns)

th.enter().append("th");
    th.text(function(d) { return d });
th.exit().remove()

// creating a row for each object in the data
var rows = tbody.selectAll('tr')
    .data(function(d) { return d; })

rows.enter().append("tr");
rows.attr('data-row',function(d,i){return i});
rows.exit().remove();   

// creating a cell for each column in the rows
var cells = rows.selectAll("td")
        .data(function(row) {
    return columns.map(function(key) {
                return {key:key, value:row[key]};
    });
        })

cells.enter().append("td");
cells.text(function(d) { return d.value; })
    .attr('data-col',function(d,i){return i})
    .attr('data-key',function(d,i){return d.key});
cells.exit().remove();

return tbl;
};

tbl.columns = function(_) {
if (!arguments.length) return columns;
columns = _;
return this;
};

return tbl;
};

此表可以被称为如下:

/// new table
var t = d3.table();

/// loading data
d3.csv('reusable.csv', function(error,data) {
    d3.select("body")
    .datum(data.filter(function(d){return d.price<850})) /// filter on lines
    .call(t)
});

其中reusable.csv文件是这样的:

date,price
Jan 2000,1394.46
Feb 2000,1366.42
Mar 2000,1498.58
Apr 2000,1452.43
May 2000,1420.6
Jun 2000,1454.6
Jul 2000,1430.83
Aug 2000,1517.68
Sep 2000,1436.51

和列数可以通过更新

t.columns(["price"]); 
d3.select("body").call(t);

问题是,在更新创建与THEAD和TBODY另一个表,因为表的创建是在函数内部。

我怎么能说“ 创建表只有一次 ,然后更新”?

另一个问题是: 我怎么可以过滤使用函数内的方法行

Answer 1:

问题是这些三行代码:

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

它总是追加新表,THEAD和TBODY元素到您的文档。 这里是你如何能做到这一点条件,只有当这些元素不存在(你举的例子同样创建了div.header元素):

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');

的全选()。数据([0])。输入()。追加()图案有条件创建单个元件,如果没有找到它。 所引用的实施例中使用的数据([TRUE]),但具有单个元件的任何阵列都行。

要筛选从你的函数中的嵌套的数据,更改数据通话(),并通过这样的选择数据的过滤子集:

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

祝好运!



文章来源: Updating an HTML table in d3.js using a reusable chart