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

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

问题描述

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

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

谢谢x

推荐答案

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

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

当前选择的 option 索引保存在 select 元素上名为 selectedIndex 的属性中.选择是数组,因此可以直接访问元素(例如,selection[0][0]).每个 option 元素都将绑定数据,存储在名为 __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__;
}

为了可读性并希望能帮助您理解上面的代码,我还想包含以下替代语法:

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天全站免登陆