在 d3 中为数据列表创建元素

Create elements for datalist in d3

本文关键字:列表 创建 元素 数据 d3      更新时间:2023-09-26

我正在尝试通过填充 D3 中 csv 文件中的条目来将选项元素添加到数据列表中。据我了解,我已经选择了我的数据列表,用 NAME 列中的条目加载了 csv,绑定了我的数据,并且应该使用带有数据值的选项附加到数据列表中。我不太确定为什么没有制作元素,我认为这与我的数据处理方式有关。

d3.select("datalist")
.data(d3.csv("Input/domain_data.csv").row(function(d){return d.NAME}))
.enter()
.append("option")
.attr("value", function(d){return d})

首先,d3.csv是异步的,这意味着您需要设置回调并等待响应到达。其次,您需要在选择<option>上调用data,即:selectAll('option')能够附加到它们。

// Start off by doing an HTTP request to a server:
d3.csv('path/to/file.csv')
  .row(function (d) { return d.NAME })
  .get(function (error, rows) {
    // The response from the server has arrived (maybe check for errors too?).
    // Let's create an empty selection of options inside a datalist:
    d3.select('datalist').selectAll('option')
      .data(rows) // performing a data join
      .enter() // extracting the entering selection
      .append('option') // adding an option to the selection of options
      .attr('value', function (d) { return d; }); // add attribute
  });