我有
<select id="x">
<option value="5">hi</option>
<option value="7">hi 2</option>
</select>
我想要一个 javascript 函数,使我能够选择和显示 <option>
默认为 id。换句话说,我想做一个 setOption(5)
和 <option>
值“5”作为默认值显示在组合框中。
这可能吗?
最佳答案
如果可以的话,用 ES6...
function setOption(selectElement, value) {
return [...selectElement.options].some((option, index) => {
if (option.value == value) {
selectElement.selectedIndex = index;
return true;
}
});
}
...否则...
function setOption(selectElement, value) {
var options = selectElement.options;
for (var i = 0, optionsLength = options.length; i < optionsLength; i++) {
if (options[i].value == value) {
selectElement.selectedIndex = i;
return true;
}
}
return false;
}
setOption(document.getElementById('my-select'), 'b');
如果返回false
,则无法找到该值:)
关于javascript - 按值选择<select>项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4324141/