JavaScript:根据选项文本设置下拉列表选定项

use*_*477 41 javascript

说我有一个这样的下拉列表:

<select id="MyDropDown">
    <option value="0">Google</option>
    <option value="1">Bing</option>
    <option value="2">Yahoo</option>
</select>
Run Code Online (Sandbox Code Playgroud)

我想根据选项文本设置选定的值,而不是使用javascript设置值.我该怎么做呢?例如,使用c#我可以执行类似下面示例的操作,并选择"Google"选项.

ListItem mt = MyDropDown.Items.FindByText("Google");
if (mt != null)
{
   mt.Selected = true;
}
Run Code Online (Sandbox Code Playgroud)

在此先感谢您的帮助!

Gab*_*ams 86

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;
    }
}
Run Code Online (Sandbox Code Playgroud)


Dan*_*kin 13

一个现代的选择:

const textToFind = 'Google';
const dd = document.getElementById ('MyDropDown');
dd.selectedIndex = [...dd.options].findIndex (option => option.text === textToFind);
Run Code Online (Sandbox Code Playgroud)


jan*_*hii 5

您可以遍历select_obj.options.每个选项对象中都有一个#text方法,您可以使用它来比较您想要的并设置select_obj的selectedIndex.