为选择选项选择了 javascript 集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8874558/
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
javascript set selected for select option
提问by Nomad
I am dynamically generating dropdowns e.g.someDropDown0, someDropDown1, someDropDown2 ...etc and write it a div in page . I want to know how can set the "selected" option value to onChange of the drop.
我正在动态生成下拉菜单 egsomeDropDown0, someDropDown1, someDropDown2 ...etc 并在 page 中写一个 div 。我想知道如何将“selected”选项值设置为 drop 的 onChange。
The reason when i add a new drop down via button the value of old one is resetted to "Select one".
当我通过按钮添加新下拉菜单时,旧下拉菜单的值被重置为“选择一个”的原因。
Need a onChange which will set the selected value as "Selected" so the selected values stays there.
需要一个 onChange 将选定的值设置为“选定”,以便选定的值保持在那里。
<select id="someDropDown0" onChange=setVak(this, this.id)>
<option value="Select One" selected>Select One</option>
<option value="12">AB</option>
<option value="13">CD</option>
<option value="15">EF</option>
<option value="20">GH </option>
<option value="21">IJ </option>
<option value="22">LM </option>
</select>
function setval(optionVal, optionId)
{
var dd = document.getElementById(optionId);
for (var i = 0; i < dd.options.length; i++)
{
if (dd.options[i].text === optionVal.text)
{
dd.selectedIndex = i;
break;
}
}
}
Please help. Thanks
请帮忙。谢谢
采纳答案by Flo
If I got you right and you are adding new options to an existing select box: rather than an some kind of "onchange" behaviour (subtree modification actually), your may want to alter the code that appends new select options.
如果我猜对了,并且您正在向现有选择框添加新选项:而不是某种“onchange”行为(实际上是子树修改),您可能想要更改附加新选择选项的代码。
See these example functions for reference:
请参阅这些示例函数以供参考:
回答by RobG
Setting the defaultSelectedproperty of the appropriate option element to true should do the trick:
将相应选项元素的defaultSelected属性设置为 true 应该可以解决问题:
> if (dd.options[i].text === optionVal.text)
> {
dd.options[i].defaultSelected = true;
> dd.selectedIndex = i;
> break;
> }
But make sure you only have one option with it set.
但请确保您只设置了一个选项。
Or did I completely misunderstand the question?
还是我完全误解了这个问题?