Javascript 如何在javascript中的下拉列表中获取值的索引?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4633878/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 13:22:41  来源:igfitidea点击:

how to get the index of value in drop down in javascript?

javascriptdrop-down-menu

提问by Red Swan

I have dropdown list on my aspx page. I want to mannually set the selected value which in exist in the dropdown list. this value i am getting in var. i want to set this value as selected value when page get initialize. I want this in javascript. is there any property for dropdown as ddp.SelectedValue='40'..? here I don't know the index of 40 in the list.

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

回答by Mike Samuel

selectedIndexis a property of HTMLSelectElement so you can do the following:

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

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

And given an OPTION element, you can get its index using the indexproperty:

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

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

回答by bobince

I want to manually set the selected value

我想手动设置选定的值

Iterate the select's options list to get the optionyou were interested in and set selectedon it:

迭代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;
    }
}

this will select the first option with a matching value. If you have more than one option with the same value, or a multiple-select, you may need different logic.

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

This:

这个:

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

is specified by HTML5 to do the same, and has worked in most modern browsers for ages, but still fails in IE, unfortunately (even IE9).

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

回答by Swathi

<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>