【问题标题】:d3 adding html links to a column of data in a tabled3将html链接添加到表中的一列数据
【发布时间】:2016-06-22 20:02:09
【问题描述】:

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

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"]);

我想根据单元格中的值将“NAME”列中的每个值都设为指向网站的超链接。例如:如果名称列中有一个值为“my_value”的值,它将是指向“http://test/my_value”的超链接。任何帮助表示赞赏!

【问题讨论】:

    标签: javascript html d3.js href


    【解决方案1】:

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

    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"})
    

    【讨论】:

    • 非常感谢!我以前没有遇到过 .filter 方法。我假设有一种简单的方法可以修改过滤器函数以根据列名而不是索引进行过滤?
    • 当然,使用.filter(function(d, i) { return d.column === "NAME" })
    • 这里的核心解决方案非常适合根据每个返回的数据值创建 Google 搜索。像这样: .attr("href", function(d) { return "google.com/search?q=" + d["Car-name"]; })
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-08-19
    • 2016-04-20
    • 2023-03-20
    相关资源
    最近更新 更多