使用D3设置下拉菜单的默认选择 [英] Setting default selection of a dropdown menu with D3

查看:135
本文介绍了使用D3设置下拉菜单的默认选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我创建了几个月的下拉菜单作为选项,但是想要预先指定一个选项作为默认值。但是,默认选择似乎固执地仍然是列表中的第一个选项。

I created a dropdown menu of some months as options, but wanted to predesignate one option as the default value. However, the default selection seemed to stubbornly remain the first option in the list.

我尝试了下面的代码,这对我来说很有意义,因为对于任何其他属性,设置一个简单的比较就足以改变该属性的值。

I tried the below code, which made a lot of sense to me because for any other attribute, setting up a simple comparison is sufficient to alter that attribute's value.

var defaultOptionName; // desired default dropdown name
d3.select("#dropdown").append("select")
    .on("change", someFunction)
    .selectAll("option").data(dataset)
    .enter().append("option")
    .attr("value", function(d){return d;})
    .attr("selected", function(d){
         return d === defaultOptionName;
    })
    .text(function(d){ return d; });

我知道我的问题只是一个正确的语法问题,但当我试图搜索时互联网和stackoverflow,但无法弄清楚我错过了什么。

I knew that my problem was just a matter of the right syntax, but when I tried to search the internet and stackoverflow, but couldn't figure out what I was missing.

推荐答案

我发现不需要使用 .attr ,我需要使用 .property 以访问默认选择选项。只需要一个简单的替换,所以你的代码片段看起来像:

I found that instead of using .attr, I needed to use .property in order to access the default selection option. A simple substitution was all that was required, so your code snippet would look something like:

    .property("selected", function(d){ return d === defaultOptionName; })

这篇关于使用D3设置下拉菜单的默认选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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