繁体   English   中英

jQuery - 如何按文本选择下拉列表项?

[英]jQuery - How to select dropdown list item by text?

如何按文字而不是按值选择下拉列表项?

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

使用:contains() (链接)

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

演示

jQuery上有一个过滤器函数 ,您可以使用它来获取更具体的元素

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

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

我想这会为你做的伎俩......

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

这是我使用的代码(它与此处的其他建议不完全相同,并与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>

希望这可以帮助。

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

$('#country option').each(function(){
    if($(this).text() == 'India'){
        $(this).prop('selected', true).trigger('change');
    }
});
$("selecter option:contains('" + data[i].ID+ "')").attr('selected', 'selected');

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM