d3将html链接添加到表中的数据列 [英] d3 adding html links to a column of data in a table

查看:151
本文介绍了d3将html链接添加到表中的数据列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是d3和Java语言的新手,我正在尝试向指定数据列中的每个值添加一个<a>元素(具有href属性).目前,我正在使用以下代码来生成表格:

I'm new to d3 and Javascript and I am trying to add an <a> element (with an href attribute) to each value in a specified column of data. Currently I'm using the following code to produce the table:

function tabulate(data, columns) {
var table = d3.select("#data_table").append("table"),
    thead = table.append("thead"),
    tbody = table.append("tbody");

// append the header row
thead.append("tr")
    .selectAll("th")
    .data(columns)
    .enter()
    .append("th")
    .text(function(column) {
        return column;
    })
    .on('click', function (d) {
        rows.sort(function (a, b) {
            if (isNaN(a[d])) {
                return d3.ascending(a[d], b[d]);
            }
            else {
                return b[d] - a[d];
            }
        });
    });
// create a row for each object in the data
var rows = tbody.selectAll("tr")
    .data(data)
    .enter()
    .append("tr");

// create a cell in each row for each column
var cells = rows.selectAll("td")
    .data(function(row) {
        return columns.map(function(column) {
            return {
                column: column, value: row[column]
            };
        });
    })
    .enter()
    .append("td")
    .html(function(d) {
        return (d.value);
    });

return table;
}
//render the data
tabulate(data, ["NAME", "1", "2", "3", "4"]);

我想根据单元格中的值,使名称"列中的每个值成为指向网站的超链接. EG:如果名称列中有一个值"my_value",它将是指向" http://test/的超链接. my_value ".感谢您的帮助!

I want to make every value in the "NAME" column a hyperlink to a website based on the value in the cell. E.G.: If there is a value in the name column that is "my_value", it will be a hyperlink to "http://test/my_value". Any help is appreciated!

推荐答案

您必须在过滤数据后附加一个链接:

You have to append a link after filtering the data like that :

cells.filter(function(d, i) { return i === 0})
    .append("a")
    .attr("href", function(d) {
        return "http://test/" + d.value;
    })
    .html(function(d) {
        return (d.value);
    });

请参见 https://jsfiddle.net/o64e570x/1/

还可以使用

 cells.filter(function(d, i) { return d.column === "NAME"})

这篇关于d3将html链接添加到表中的数据列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆