15

我正在尝试向我的 d3 可视化添加一个下拉菜单。问题是事件监听器不会在选择任何选项时被调用。另外,如何访问所选选项的值?以下是我的代码片段..

d3.text("uniqueTeams.php",function(json){
    var dd=JSON.parse(json);
    var b= d3.select("#s4").select("#shru");
    var u=b.append("select");
    var t=u.selectAll("option").data(dd).enter().append("option")
        .attr("value",function(d){return d.teamShotID;})
        .text(function(d){return d3.select(this).node().__data__.teamShotID;});
    t.on("change",change);
});
function change(value)
{
    console.log("team",value);
}
change();​​​​

谢谢

4

2 回答 2

36

您需要添加.on("change")select元素,而不是option元素。

var select  = d3.select("#shru").append("select").on("change", change),
    options = select.selectAll('option').data(dd); // Data join

// Enter selection
options.enter().append("option").text(function(d) { return d.teamShotID; });

当前选定的option索引保存在元素上调用的属性selectedIndexselect选择是数组,因此可以直接访问元素(例如,selection[0][0]。每个option元素都将绑定数据,存储在一个名为的属性中__data__

function change() {
    var selectedIndex = select.property('selectedIndex'),
        data          = options[0][selectedIndex].__data__;
}

编辑:为了可读性并希望能帮助您理解上面的代码,我还想包括这种替代语法:

function change() {
    var si   = select.property('selectedIndex'),
        s    = options.filter(function (d, i) { return i === si }),
        data = s.datum();
}
于 2012-08-10T18:16:11.903 回答
0

希望这可以指导你...

      var dispatch = d3.dispatch("load", "countrychange");
  d3.csv("data/ERSreputationBlocked.csv",type, function (error, country) {
      if (error) throw error;
      var countryById = d3.map();
      country.forEach(function (d) { countryById.set(d.id, d); });
      dispatch.load(countryById);
      dispatch.countrychange(countryById.get("PH"));
      //console.log(country);
  });
  dispatch.on("load.menu", function(countryById) {
      var select = d3.select("body")
        .append("div")
        .append("select")
        .on("change", function () { dispatch.countrychange(countryById.get(this.value)); });

      select.selectAll("option")
        .data(countryById.values())
        .enter().append("option")
        .attr("value", function (d) { return d.id; })
        .text(function (d) { return d.Country; });

      dispatch.on("countrychange.menu", function (country) {
          select.property("value", country)
          //loading the value based on the selected data
          var svg1 = d3.select("body").append("svg1")
                .attr("width", width)
                .attr("height", height)
          //end of selection

         console.log(country);
      });
  });
  //end of drop down

  function type(d) {
      d.total = d3.sum(d.value, function (k) { return d[k] = +d[k]; });
      return d;
  }
于 2013-11-28T07:58:38.210 回答