JavaScript:基于选项文本设置下拉选择项
假设我有这样一个下拉列表:JavaScript:基于选项文本设置下拉选择项,javascript,Javascript,假设我有这样一个下拉列表: <select id="MyDropDown"> <option value="0">Google</option> <option value="1">Bing</option> <option value="2">Yahoo</option> </select> 提前感谢您的帮助 var textToFind='Google'; var tex
<select id="MyDropDown">
<option value="0">Google</option>
<option value="1">Bing</option>
<option value="2">Yahoo</option>
</select>
提前感谢您的帮助 var textToFind='Google';
var textToFind = 'Google';
var dd = document.getElementById('MyDropDown');
for (var i = 0; i < dd.options.length; i++) {
if (dd.options[i].text === textToFind) {
dd.selectedIndex = i;
break;
}
}
var dd=document.getElementById('MyDropDown');
对于(变量i=0;i
您可以循环选择对象选项。每个选项对象中都有一个#text方法,您可以使用该方法与所需内容进行比较,并设置select#obj的selectedIndex 现代替代方案:
const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);
这适用于最新的Chrome、FireFox和Edge,但不适用于IE11:
document.evaluate('//option[text()=“Yahoo”]”,document.iterateNext().selected='selected';
如果要忽略标题周围的空格:
document.evaluate('//option[normalize space(text())=“Yahoo”]”,document.iterateNext().selected=“selected”
最好检查选项是否存在,以避免选择空选项<代码>函数selectItem(选择器,标签){const dropdown=document.querySelector(选择器)const index=Array.from(dropdown.options).findIndex(option=>option.label==label)如果(!index)返回dropdown.selectedIndex=index}selectItem('#MyDropDown',Google')
const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);