2016-04-22 34 views
0

我试图通过从D3中的csv文件填充条目来将选项元素添加到数据列表中。根据我的理解,我选择了我的datalist,将csv加载NAME列中的条目,绑定了我的数据,并且应该使用具有数据值的选项附加到数据列表。我不太确定为什么元素没有被制作,我认为它与我的数据处理方式有关。在d3中为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}) 
+0

我会冒险猜测,d3.csv是异步的,因此不会立即返回任何东西。 – Oleg

+0

将您的CSV加载到一个函数中,然后在其中添加您的选项。 –

回答

3

首先,d3.csv是异步的,这意味着你需要设置一个回调和等待为到达的响应。第二,您需要拨打data以选择<option> s,即: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 
    });