选择< select>项目的价值 [英] select <select> item by value
本文介绍了选择< select>项目的价值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有
< select id =x>
< option value =5> hi< / option>
< option value =7> hi 2< / option>
< / select>
我需要一个javascript函数,使我可以选择并显示<选项>
作为id的默认值。换句话说,我想要一个 setOption(5)
和< option>
值为5 作为默认值显示在组合框中。
这可能吗?
解决方案如果可以的话,用ES6 ...
pre $函数setOption(selectElement,value){
返回[... selectElement.options] .some((option,index)=> {
if(option.value == value){
selectElement.selectedIndex = index;
return真;
}
});
}
pre $函数setOption(selectElement,value){
返回[... selectElement.options] .some((option,index)=> {
if(option.value == value){
selectElement.selectedIndex = index;
return真;
}
});
}
...否则...
函数setOption(selectElement,value){
var options = selectElement.options;
for(var i = 0,optionsLength = options.length; i< optionsLength; i ++){
if(options [i] .value == value){
selectElement.selectedIndex =一世;
返回true;
}
}
返回false;
}
setOption(document.getElementById('my-select'),'b');
查看全文