D3 将图像追加到表头的方法



在HTML中,我通常将图像添加到表头的方式如下:

<th><img src= image.png alt="" height=20 width=20></img></th>

HTML方式非常简单直观。然而,我已经切换到 D3 来创建表,我的标头代码是:

var columns = ['Column X', 'Column Y', 'Column Z']
var table = d3.select('#table_container').append('table'),
    thead = table.append('thead')
    tbody = table.append('tbody');
thead.append('tr')
    .selectAll('th')
    .data(columns)
    .enter()
    .append('th')
        .text(function(column) { return column; });

我的问题是:如何使用 d3 将图像附加到表标题?我打算为每个标题使用不同的图像。

感谢您的阅读

只需附加一个img并使用src作为其属性:

var columns = [
    {src:"http://iconbug.com/data/3a/256/77c71e95885bf94c06c7c68ccb63b131.png"}, 
    {src:"http://iconbug.com/data/3a/256/9f8cd17bf12b1667d6c4b31b889b3034.png"}, 
    {src:"http://iconbug.com/data/b4/256/4ece97792658df143eb693c23bb991f3.png"}
];
var table = d3.select("body").append('table');
var thead = table.append('thead');
thead.append('tr')
    .selectAll('th')
    .data(columns)
    .enter()
    .append('th')
    .append('img')
    .attr('src', function(d) {
        return d.src;
    });
table, th {
   border: 1px solid gray;
}
<script src="https://d3js.org/d3.v4.min.js"></script>

相关内容

最新更新