我有这种可重复使用的模式来创建一个受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的表,因为表的创建在函数内部。
如何说“只创建一次,然后更新”?
另一个问题是:如何使用函数中的方法过滤线条?
答案 0 :(得分:4)
问题在于这三行代码:
// 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');
selectAll()。data([0])。enter()。append()模式有条件地创建单个元素(如果找不到)。引用的示例使用数据([true]),但任何具有单个元素的数组都可以。
要过滤函数中的嵌套数据,请更改对data()的调用,并传递选定数据的过滤子集,如下所示:
var rows = tbody.selectAll('tr').data(tbody.data()[0].filter(function(d) {
return d.price > 1400;
}));
祝你好运!