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

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

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

使用:contains() (链接)

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

演示

jQuery上有一个filter函数 ,您可以使用它来获取具有更具体内容的元素

 $("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"); });  

希望这可以帮助。

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

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