使用d3.js添加下拉菜单 [英] Adding drop down menu using d3.js

查看:1833
本文介绍了使用d3.js添加下拉菜单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为我的d3可视化添加一个下拉菜单。问题是,在选择任何选项时,不会调用eventlistener。另外,如何访问所选的选项的值?以下是我的代码片段。

I am trying to add a drop down menu to my d3 visualization. The problem is that the eventlistener does not get invoked on selecting any of the options. Also, how can I access the value of the option selected? Following is a snippet of my code..

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();​​​​

>

推荐答案

您需要将 .on(change) code>选择元素,而不是选项元素。

You need to add the .on("change") to the select element, not the option elements.

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; });

当前选择的选项元素上的 selectedIndex 属性。 选择是数组,因此可以直接访问元素(例如, selection [0] [0] 。每个选项元素都会绑定数据,存储在 __ data __

The currently selected option index is kept in a property called selectedIndex on the select element. Selections are arrays, so elements can be accessed directly (e.g., selection[0][0]). Each option element will have data bound to it, stored in a property called __data__:

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



编辑:为了可读性并希望帮助您理解上面的代码, d喜欢也包括这个替代语法:

For readability and hopefully to help you understand the code above, I'd like to also include this alternative syntax:

function change() {
    var si   = select.property('selectedIndex'),
        s    = options.filter(function (d, i) { return i === si }),
        data = s.datum();
}

这篇关于使用d3.js添加下拉菜单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆