2016-02-08 231 views
1

如何过滤菜单,我有以下普拉克 https://plnkr.co/edit/gDbUE99nNNMtYp9IpR1d?p=info和我在努力让我的下拉菜单中使用嵌套数据的工作。 IVE生成的菜单从第一水平巢(“起点”),其示出了从第二电平巢(“纳特”)产生的国籍的列表。我想用菜单加载与每个“起点”相关的不同'Nat'。D3基于嵌套数据

以前我创造了我这样的菜单,但它似乎并没有与“nested_data”合作。 d3.filter()是否错误?

list.on('change', function() { 
     var selected = d3.select(this).select("select").property("value") 
     var cd = nested_data.filter(function(d) { 
      return (selected == d.key) 
     }); 
    updateNested_data(cd) 
    }); 

... 

var filter = nested_data.filter(function(d) { 
     return ("Berkner Island" == d.key) 
    }); 
    updateNested_data(filter) 

我在更新函数中也遇到了exit()问题,我想因为我过早地绑定了我的数据?但对于这个问题,我想专注于如何让菜单正常工作。

的完整代码

d3.csv("data.csv", function(CSV) { 

    var nested_data = d3.nest() 
     .key(function(d) { 
     return d['starting point']; 
     }) 
     .key(function(d) { 
     return d.Nat; 
     }) 
     .entries(CSV); 

    // CREATE DROPDOWN 
    var list = d3.select("#opts") 

    list.append("select").selectAll("option") 
     .data(nested_data) 
     .enter().append("option") 
     .attr("value", function(d) { 
     return d.key; 
     }) 
     .text(function(d) { 
     return d.key; 
     }); 

    // MENU 
    list.on('change', function() { 
     var selected = d3.select(this).select("select").property("value") 
     var cd = nested_data.filter(function(d) { 
      return (selected == d.key) 
     }); 
    updateNested_data(cd) 
    }); 

    // CONFIG 
    var canvas = d3.select('#explorers').data(nested_data) 

    // BIND, ENTER, REMOVE 
    function updateNested_data(nested_data) { 

     var country = canvas.selectAll(".country") 

     var countryEnter = country 
     .data(function(d) { 
      return d.values 
     }) 
     .enter().append('div') 
     .attr('class', 'country') 

     countryEnter 
     .append("p") 
     .attr('class', 'label') 
     .style('font-weight', 'bold') 
     .text(function(d) { 
      return d.key; 
     }) 

     country.exit().remove(); 

    }; 

    //FILTER 
    var filter = nested_data.filter(function(d) { 
     return ("Berkner Island" == d.key) 
    }); 

    // UPDATE 
    updateNested_data(filter) 

}); 

回答

1

这是没有问题的任何地方,除非你进入的方式和退出:

function updateNested_data(cd) { 
     //set the data to the selection 
     var country = canvas.selectAll(".country").data(cd.values) 

     var countryEnter = country 

      .enter().append('div') 
      .attr('class', 'country') 

     countryEnter 
      .append("p") 
      .attr('class', 'label') 
      .style('font-weight', 'bold') 
      .text(function(d) { 
       return d.key; 
      }) 
     //exit on selection 
     country.exit().remove(); 

    }; 

工作代码here

+0

魔术师! .pop()在这方面做了什么? – user3821345

+0

我只是采取的第一个元素的数组array.pop()将拿出最后一个元素 – Cyril

+0

我已经改变了我进入和退出的方式,但它不工作。在普拉克您使用.pop()和它的作品,但我该怎么办,如果我不想拿出最后一个元素? – user3821345