Javascript jQuery - 如何通过文本选择下拉列表项?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4757198/
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
jQuery - How to select dropdown list item by text?
提问by nunu
How would I select my dropdown list item by text rather than value?
我将如何通过文本而不是值来选择我的下拉列表项?
I want to select a dropdown item by text with jQuery.
我想用 jQuery 通过文本选择一个下拉项。
回答by BrunoLM
There is a filter function on jQuerythat you can use to get elements with something more specific
jQuery 上有一个过滤器功能,您可以使用它来获取具有更具体内容的元素
$("select option").filter(function() {
return $(this).text() == "text_to_select";
});
This is going to return all options with the "text_to_select" in the text.
这将返回文本中带有“text_to_select”的所有选项。
回答by Vivek
i think this will do the trick for you...
我认为这对你有用...
$("#selectId").find("option:contains('text')").each(function(){
if( $(this).text() == 'Text that should be matched' ) {
$(this).attr("selected","selected");
}
});
回答by Mike Gledhill
Here's the code I use (it's not quite the same as the other suggestions here, and works with jQuery v1.8.3)
这是我使用的代码(它与此处的其他建议不太相同,并且适用于 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>
Hope this helps.
希望这可以帮助。
回答by Zeeshan
I had a similar scenario with dropdowns for country, state and city. Country had "India" as well as "British Indian Ocean Territory". The issue with :contains()
is that it attempts on both matches. I did something like:
我有一个类似的场景,包括国家、州和城市的下拉菜单。国家有“印度”和“英属印度洋领地”。问题:contains()
在于它尝试了两场比赛。我做了类似的事情:
$('#country option').each(function(){
if($(this).text() == 'India'){
$(this).prop('selected', true).trigger('change');
}
});
回答by Aqib Shehzad
$("selecter option:contains('" + data[i].ID+ "')").attr('selected', 'selected');