如何设置出现在下拉菜单中的默认值? [英] How to set default value appearing in dropdown?

查看:183
本文介绍了如何设置出现在下拉菜单中的默认值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看到答案,其中说为此:

I have seen this answer which says to do this:

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

但这对我不起作用.我正在尝试创建一个简单的下拉菜单,并将默认值创建为最初出现在下拉菜单中的文本.这就是我正在做的:

But this isn't working for me. I'm trying to create a simple drop down and create a default value to be the text that initially appears on the drop down. This is what I'm doing:

    var dropdown = d3.select("#dropDown")
        .insert("select", "svg")
        .attr('id', 'dropDownId')
        .on("change", dropdownChange);

    dropdown.selectAll("option")
        .data(cols)
        .enter().append("option")
        .attr("value", function (d) { return d; })
        .text(function (d) {
            return d;
        });
        dropdown.property("selected", "some default value");

出于某些原因,cols中的第一个值仍然显示出来.我如何实现我的目标?

For some reasons, the first value in cols is what still shows up. How can I accomplish my goal?

推荐答案

执行此操作时...

dropdown.property("selected", "some default value");

...您必须问自己:什么是下拉列表?很明显,这是D3选择,但是什么选择?

... you have to ask yourself: what is dropdown? It's a D3 selection, that's clear, but what selection?

让我们看看:

var dropdown = d3.select("#dropDown")
    .insert("select", "svg")
    //etc...

因此,下拉是指< select> ,而不是选项.

Therefore, dropdown refers to the <select>, not to the options.

最重要的是,您无法设置...

On top of that, you cannot set...

dropdown.property("selected", "some default value");

selected 属性是给定选项的布尔值.

解决方案:为< option> s创建一个新选择:

Solution: create a new selection for the <option>s:

var options = dropdown.selectAll("option")
    .data(cols)
    .enter()
    //etc...

然后:

options.property("selected", function(d){
    return d === "some default value");
});

其中 d ===某些默认值" 将为每个数据返回 true false .

Where d === "some default value" will return true or false for each datum.

或者,您无需命名选择(但这是个好主意),只需将该方法添加到链中即可.

Alternatively, you don't need to name the selection (but it's a good idea doing so), just add that method to the chain.

这是一个演示:

var cols = ["foo", "bar", "baz", "foobar", "foobaz"]

var dropdown = d3.select("body")
  .append("select")
  .attr('id', 'dropDownId');

var options = dropdown.selectAll("option")
  .data(cols)
  .enter()
  .append("option")
  .attr("value", function(d) {
    return d;
  })
  .text(function(d) {
    return d;
  });

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

<script src="https://d3js.org/d3.v5.min.js"></script>

这篇关于如何设置出现在下拉菜单中的默认值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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