JavaScript:根据选项文本设置下拉选择项

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3989324/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:02:11  来源:igfitidea点击:

JavaScript: set dropdown selected item based on option text

javascript

提问by user1017477

say I have a dropdown list like this:

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

<select id="MyDropDown">
    <option value="0">Google</option>
    <option value="1">Bing</option>
    <option value="2">Yahoo</option>
</select>

and I want to set the selected value based on the option text, not the value with javascript. How can I go about doing this? For example, with c# I can do something like the example below and the the option with "Google" would be selected.

我想根据选项文本设置选定的值,而不是使用 javascript 的值。我该怎么做呢?例如,使用 c#,我可以执行以下示例中的操作,并且将选择带有“Google”的选项。

ListItem mt = MyDropDown.Items.FindByText("Google");
if (mt != null)
{
   mt.Selected = true;
}

Thanks in advance for any help!

在此先感谢您的帮助!

回答by Gabriel McAdams

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;
    }
}

回答by Danyal Aytekin

A modern alternative:

现代替代方案:

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

回答by janechii

You can loop through the select_obj.options. There's a #text method in each of the option object, which you can use to compare to what you want and set the selectedIndex of the select_obj.

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