【问题标题】:jQuery - How to select dropdown list item by text?jQuery - 如何按文本选择下拉列表项?
【发布时间】:2011-01-21 09:26:24
【问题描述】:

如何通过文本而不是值来选择我的下拉列表项?

我想用 jQuery 通过文本选择一个下拉项。

【问题讨论】:

    标签: javascript jquery jquery-selectors


    【解决方案1】:

    使用:contains()(link)

    $("select option:contains(text)").attr('selected', true);
    

    demo

    【讨论】:

    • 如果需要做变量:var text = "Item 1"; $("select option:contains(" + text + ")").attr('selected', true);
    • 这很好用,除非你有类似的物品。例如,如果您搜索“item”并且选项是“item 1”、“item 2”等,那么您将获得多个结果
    • 对于较新版本的 jquery (1.6.1+?),使用 prop('selected',true) 代替 attr('selected',true)
    • @PostureOfLearning : 类似项目的任何解决方案?
    • 好的,我能够做到并发布了我的答案。
    【解决方案2】:

    有一个filter function on jQuery,您可以使用它来获取更具体的元素

    $("select option").filter(function() {
        return $(this).text() == "text_to_select";
    });
    

    这将返回文本中带有“text_to_select”的所有选项。

    【讨论】:

    • 这应该是公认的答案。使用“包含”可能会匹配多个值,这可能很危险。
    【解决方案3】:

    我认为这对你有用...

    $("#selectId").find("option:contains('text')").each(function(){
      if( $(this).text() == 'Text that should be matched' ) {
        $(this).attr("selected","selected");
      }
    });
    

    【讨论】:

      【解决方案4】:

      这是我使用的代码(它与这里的其他建议不太一样,适用于 jQuery v1.8.3)

      var userToSearchFor = 'mike';   //  Select any options containing this text
      
      $("#ListOfUsers").find("option:contains('" + userToSearchFor +"')").each(function () {
         $(this).attr("selected", "selected");
      });
      
      <select id="ListOfUsers" ></select>
      

      希望这会有所帮助。

      【讨论】:

        【解决方案5】:

        我有一个类似的场景,国家、州和城市的下拉菜单。国家有“印度”以及“英属印度洋领地”。 :contains() 的问题在于它会尝试两个匹配项。我做了类似的事情:

        $('#country option').each(function(){
            if($(this).text() == 'India'){
                $(this).prop('selected', true).trigger('change');
            }
        });
        

        【讨论】:

          【解决方案6】:
          $("selecter option:contains('" + data[i].ID+ "')").attr('selected', 'selected');
          

          【讨论】:

            猜你喜欢
            • 2015-02-14
            • 1970-01-01
            • 1970-01-01
            • 2012-08-29
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            相关资源
            最近更新 更多