根据下拉菜单返回数据?

时间:2013-05-17 14:28:22

标签: d3.js

我正在构建一个基本的散点图,我想基于下拉选择突出显示我的绘图中的特定点。我的代码如下所示:

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"]

1 个答案:

答案 0 :(得分:3)

使用this.selectedIndex

访问它
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"}
        ;})
});