我想使用jquery选择一个select元素的项目,而不是它的值。
我找到了这段代码:
$("#myselect").val("Some oranges").attr("selected", "selected");
但我尝试使用我的选择选项文本,但它只适用于选项值。
我该怎么做?
答案 0 :(得分:1)
类似的东西:
$("#myselect option").filter(function(){
return $(this).text() == "Some oranges";
}).attr("selected", "selected");
答案 1 :(得分:1)
您可以使用:contains()
伪选择器查找包含文本值的选项
$("#myselect option:contains('Some oranges')").attr("selected" , "selected");
此外,如果您使用的是jQuery 1.6+,请使用.prop()
代替.attr()
$("#myselect option:contains('Some oranges')").prop("selected", true);
<强> Example on jsfiddle 强>
答案 2 :(得分:0)
jQuery :contains选择器区分大小写
$("#myselect option:contains(Some oranges)").attr("selected", "selected");
根据其评论,扩展包含带有econtains的选择器,用于不区分大小写的完全匹配或icontains,用于不区分大小写的部分匹配:
$.expr[":"].econtains = function(obj, index, meta, stack){
return (obj.textContent || obj.innerText || $(obj).text() || "").toLowerCase() == meta[3].toLowerCase();
}
$.expr[':'].icontains = function(obj, index, meta, stack){
return (obj.textContent || obj.innerText || jQuery(obj).text() || '').toLowerCase().indexOf(meta[3].toLowerCase()) >= 0;
};