我正在尝试使用 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; } }
];
目前采用这种格式,我收到错误: “无法在“Element”上执行“querySelectorAll”:“xhtml:th”不是有效的选择器。”
最佳答案
我没有充分的理由为什么 .selectAll('xhtml:td')
不起作用,可能是不支持。
但是我尝试了以下方法,并且想与您分享:
var table = svg.append("foreignObject")
.attr("width", 480)
.attr("height", 500)
.append("xhtml:body")//append body to foreign object(this is missing in your code)
然后您可以简单地附加元素,就像您在 d3 中所做的那样,如下所示。
table.append("table")
// append header row
table.append('thead').append('tr')
.selectAll('th')//select using normal selector without xhtml
.data(scope.columns).enter()
工作代码here
希望这有帮助!
关于javascript - d3 - 在 svg 元素之上渲染 html 表格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34112331/