【发布时间】:2011-12-09 13:44:48
【问题描述】:
我的 aspx 页面上有下拉列表。我想手动设置下拉列表中存在的选定值。这个值我在 var 中得到。我想在页面初始化时将此值设置为选定值。我想要这个在 javascript 中。是否有任何下拉属性为 ddp.SelectedValue='40'..?这里我不知道列表中40的索引。
【问题讨论】:
我的 aspx 页面上有下拉列表。我想手动设置下拉列表中存在的选定值。这个值我在 var 中得到。我想在页面初始化时将此值设置为选定值。我想要这个在 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>
【讨论】: