繁体   English   中英

如何在javascript中下载值的索引?

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

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

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>

我想手动设置所选的值

迭代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)。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM