【问题标题】:d3 table when not to selectd3表什么时候不选择
【发布时间】:2014-01-07 13:03:44
【问题描述】:

我正在学习 D3 中的表格,我的问题是何时使用“.select()”:

例如,在建立圆圈时:

var circles = svg.selectAll("circle")
    .data(dataSet)
    .enter()
    .append("circle")
    .attr("r", 2.5)
    .attr("cx", function(d){ return d.x})
    .attr("cy", function(d){ return d.y});

选择圆圈(空)-> 附加圆圈

但是当我在建一张桌子时,

下面的代码直接追加表格,没有先select("table")。与“tr”相同。

function tabulate(data, columns) {
    var table = d3.select("#container").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; });

(来自"creating a table from csv"的代码)

为什么下面的代码不起作用?

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

提前致谢,

【问题讨论】:

    标签: javascript d3.js html-table


    【解决方案1】:

    当您已经知道存在特定元素并且想要获取对它的引用并对其进行更改(或附加子元素)时,通常会使用 Select。既然知道 div 中没有 table 标签,那么选择它就没有意义了。

    如果您确定表格标签是否存在并且您想根据其他一些数据创建它,您可以修改您的代码,使其看起来像这样:

    var table = d3.select("#container")
        .select("table")
        .data(['hi'])
        .enter()
        .append("table"),
        thead = table.append("thead"),
        tbody = table.append("tbody");
    

    但是,正如作者在this answer 中所解释的那样,select 和 selectAll 的工作方式存在细微差别。我的示例代码直接在正文内而不是在 div 内创建表标记。因此,除非您确实将元素绑定到数据,否则最好直接附加。

    【讨论】:

      猜你喜欢
      • 2019-07-16
      • 1970-01-01
      • 1970-01-01
      • 2011-11-23
      • 1970-01-01
      • 2015-12-12
      • 1970-01-01
      • 2020-01-09
      相关资源
      最近更新 更多