【问题标题】:how to get the index of value in drop down in javascript?如何在javascript中获取下拉列表中的值索引?
【发布时间】:2011-12-09 13:44:48
【问题描述】:

我的 aspx 页面上有下拉列表。我想手动设置下拉列表中存在的选定值。这个值我在 var 中得到。我想在页面初始化时将此值设置为选定值。我想要这个在 javascript 中。是否有任何下拉属性为 ddp.SelectedValue='40'..?这里我不知道列表中40的索引。

【问题讨论】:

    标签: javascript drop-down-menu


    【解决方案1】:

    selectedIndex 是 HTMLSelectElement 的一个属性,因此您可以执行以下操作:

    <select id="foo"><option>Zero<option>One<option>Two</select>
    <script>
    document.getElementById('foo').selectedIndex = 1;  // Selects option "One"
    </script>
    

    给定一个 OPTION 元素,您可以使用 index 属性获取它的索引:

    <select><option>Zero<option id="bar">One<option>Two</select>
    <script>
    alert(document.getElementById('bar').index);  // alerts "1"
    </script>
    

    【讨论】:

    • 不,我想根据我的示例获得 40 的索引。如何获得?
    • @Lalit,我不确定我是否理解,但我更新了帖子以解释如何从选项转到其索引。给定字符串“40”,您想要具有该值的选项的索引吗?或者给定数字 40,您想要具有该索引的选项吗?
    【解决方案2】:

    我要手动设置选中的值

    迭代select的选项列表以获取您感兴趣的option并在其上设置selected

    var options= document.getElementById('ddp').options;
    for (var i= 0; n= options.length; i<n; i++) {
        if (options[i].value==='40') {
            options[i].selected= true;
            break;
        }
    }
    

    这将选择具有匹配值的第一个选项。如果您有多个具有相同值的选项或多选,则可能需要不同的逻辑。

    这个:

    document.getElementById('ddp').value= '40';
    

    由 HTML5 指定做同样的事情,并且已经在大多数现代浏览器中工作了很长时间,但在 IE 中仍然失败,不幸的是(甚至是 IE9)。

    【讨论】:

    • 鉴于这个问题,这似乎是正确的答案。也许 没有足够的 jQuery ;-) ps,后一种方法在 IE 10 预览版中有效。
    【解决方案3】:
    <script type="text/javascript" src="http://ajax.aspnetcdn.com/ajax/jQuery/jquery 1.6.2.min.js" />
    <script language="JavaScript">
        $(function() {
            quickSelect();
            // Handler for .ready() called.
        });
        function quickSelect() {
            var bnd = "40";
            if (bnd != "") {
                $("#ddp option[value='" + bnd + "']").attr("selected", "selected");
            }
        }
    </script>
    

    【讨论】:

      猜你喜欢
      • 2020-11-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-11-29
      • 1970-01-01
      • 1970-01-01
      • 2018-10-05
      • 2022-11-02
      相关资源
      最近更新 更多