2013-05-17 75 views
5

我正在構建一個基本散點圖,我想根據下拉選擇來突出顯示我的繪圖中的特定點。我的代碼如下所示:根據下拉菜單返回數據?

fill_arr = fill.range(); 
labels = ["A", "B", "C", "D"]; 
options = [0, 1, 2, 3]; 

// Build the dropdown menu 
d3.select("#drop") 
    .append("select") 
    .selectAll("option") 
    .data(options) 
    .enter() 
    .append("option") 
    // Provide available text for the dropdown options 
    .text(function(d) {return labels[d];}) 

d3.select('select') 
    .on("change", function() { 
    // HOW CAN I GET THE OPTION THAT THE USER HAS SELECTED FROM THE DROPDOWN? 
    key = 0 // <- I can do this manually, but I want to get the label the user has selected 
    d3.selectAll('circle') 
     .transition() 
     .duration(300) 
     .ease("quad") 
     .attr('r', 5) 
     .attr('cx', function(d) {return d.x;}) 
     .attr('cy', function(d) {return d.y;}) 
     // if a data point is selected highlight other 
     // data points of the same color 
     .style('fill', function(d, i) { 
      if (d.label == key) 
      {return fill_arr[key]} 
      else {return "#ccc"} 
     ;}) 
    }); 

我的問題是我不知道如何確定用戶從下拉列表中選擇了什麼。我如何確定用戶選擇了哪個選項["A", "B", "C", "D"]?它使用this.selectedIndex

+0

可能DUP:http://stackoverflow.com/questions/11903709/adding-drop-down-menu-using-d3-js – mccannf

+0

感謝您的幫助。我確實看到了這個問題,不幸的是,我仍然無法弄清楚如何獲取用戶選擇的數據。 – user1728853

+2

'key = this.selectedIndex'工作嗎? – mccannf

回答

3

訪問:

d3.select('select') 
    .on("change", function() { 

    key = this.selectedIndex; 

    d3.selectAll('circle') 
     .transition() 
     .duration(300) 
     .ease("quad") 
     .attr('r', 5) 
     .attr('cx', function(d) {return d.x;}) 
     .attr('cy', function(d) {return d.y;}) 
     // if a data point is selected highlight other 
     // data points of the same color 
     .style('fill', function(d, i) { 
      if (d.label == key) 
      {return fill_arr[key]} 
      else {return "#ccc"} 
     ;}) 
});