2016-04-22 38 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 
    });