在d3中为datalist创建元素

时间:2016-04-22 23:47:08

标签: javascript html csv d3.js

我试图通过填充D3中csv文件中的条目来向数据列表中添加选项元素。根据我的理解,我选择了我的datalist,使用NAME列中的条目加载csv,绑定我的数据,并且应该附加带有数据值的选项的datalist。我不太清楚为什么没有制作元素,我认为它与我的数据处理方式有关。

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

1 个答案:

答案 0 :(得分:3)

首先,d3.csv是异步的,这意味着您需要设置回调并等待以使响应到达。其次,您需要在选定的data上致电<option>,即: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
  });
相关问题