【发布时间】:2011-01-21 09:26:24
【问题描述】:
如何通过文本而不是值来选择我的下拉列表项?
我想用 jQuery 通过文本选择一个下拉项。
【问题讨论】:
标签: javascript jquery jquery-selectors
如何通过文本而不是值来选择我的下拉列表项?
我想用 jQuery 通过文本选择一个下拉项。
【问题讨论】:
标签: javascript jquery jquery-selectors
【讨论】:
有一个filter function on 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');
【讨论】: