【问题标题】:JavaScript: set dropdown selected item based on option textJavaScript:根据选项文本设置下拉所选项目
【发布时间】:2010-10-21 15:48:39
【问题描述】:

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

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

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

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

提前感谢您的帮助!

【问题讨论】:

    标签: javascript


    【解决方案1】:
    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;
        }
    }
    

    【讨论】:

      【解决方案2】:

      现代替代方案:

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

      【讨论】:

      • 最好检查选项是否存在以避免选择空选项。 function selectItem(selector, label) { const dropdown = document.querySelector(selector) const index = Array.from(dropdown.options).findIndex(option =&gt; option.label === label) if (!index) return dropdown.selectedIndex = index } selectItem('#MyDropDown', 'Google')
      【解决方案3】:

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

      【讨论】:

        【解决方案4】:

        这适用于最新的 Chrome、FireFox 和 Edge,但不适用于 IE11:

        document.evaluate('//option[text()="Yahoo"]', document).iterateNext().selected = 'selected';
        

        如果你想忽略标题周围的空格:

        document.evaluate('//option[normalize-space(text())="Yahoo"]', document).iterateNext().selected = 'selected'
        

        【讨论】:

          猜你喜欢
          • 2012-10-14
          • 2021-03-11
          • 2018-09-24
          • 1970-01-01
          • 1970-01-01
          • 2018-08-13
          • 2010-11-23
          • 1970-01-01
          相关资源
          最近更新 更多