【问题标题】:Return data based on dropdown menu?根据下拉菜单返回数据?
【发布时间】:2013-05-17 14:28:21
【问题描述】:

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

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

【问题讨论】:

  • 感谢您的帮助。我确实看到了这个问题,不幸的是,我似乎仍然无法弄清楚如何获取用户选择的数据。
  • key = this.selectedIndex 工作吗?
  • 谢谢。太精彩了。非常感谢您的帮助!像魅力一样工作!
  • @mccannf:您能否将其添加为参考答案?

标签: d3.js


【解决方案1】:

使用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"}
        ;})
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多