【发布时间】:2016-03-10 19:14:56
【问题描述】:
我正在尝试使用 d3 动态创建 html 表。它们需要可拖动并使用其他 svg 功能,因此需要在 svg 元素中创建它们。由于 svg 不允许使用表格,因此我在外部对象中创建了表格。我不能先写出 html 模板,因为我不知道数据中将传递多少行/列等。我有 html 部分工作,但它不允许我使用 'xhtml:element' 将其转换为正确的格式:
var svg = d3.select('svg');
svg.append("foreignObject")
.attr("width", 200)
.attr("height", 400);
var table = d3.select('foreignObject').append("xhtml:table");
// append header row
table.append('xhtml:thead').append('xhtml:tr')
.selectAll('xhtml:th')
.data(scope.columns).enter()
.append('xhtml:th')
.attr('class', function (d) { return d.cl; })
.text(function (d) { return d.head; });
// append body rows
table.append('xhtml:tbody')
.selectAll('xhtml:tr')
.data(scope.movies).enter()
.append('xhtml:tr')
.selectAll('xhtml:td')
.data(function (row, i) {
// evaluate column objects against the current row
return scope.columns.map(function (c) {
var cell = {};
d3.keys(c).forEach(function (k) {
cell[k] = typeof c[k] == 'function' ? c[k](row, i) : c[k];
});
return cell;
});
}).enter()
.append('xhtml:td')
.html(function (d) { return d.html; })
.attr('class', function (d) { return d.cl; });
以下是我正在测试的示例数据集:
scope.movies = [
{ title: "The Godfather", year: 1972, length: 175,
budget: 6000000, rating: 9.1 },
{ title: "The Shawshank Redemption", year: 1994,
length: 142, budget: 25000000, rating: 9.1 },
{ title: "The Lord of the Rings 3", year: 2003,
length: 251, budget: 94000000, rating: 9 }
];
scope.columns = [
{ head: 'Movie title', cl: 'title', html: function (d) { return d.title; } },
{ head: 'Year', cl: 'center', html: function (d) { return d.year; } },
{ head: 'Length', cl: 'center', html: function (d) { return d.length; } },
{ head: 'Budget', cl: 'num', html: function (d) { return d.budget; } },
{ head: 'Rating', cl: 'num', html: function (d) { return d.rating; } }
];
目前采用这种格式,我收到错误: '无法在'元素'上执行'querySelectorAll':'xhtml:th'不是有效的选择器。'
【问题讨论】:
标签: javascript html d3.js svg xhtml