2011-12-29 113 views
0

我想通過它的文本選擇一個選擇元素的項目而不是使用jquery的值。使用jquery通過文本選擇一個喜歡的選擇元素項

我發現這個代碼:

$("#myselect").val("Some oranges").attr("selected", "selected"); 

,但我嘗試用我的選擇選項的文本,但它僅與期權價值的工作。

我該怎麼辦?

回答

1

喜歡的東西:

$("#myselect option").filter(function(){ 
    return $(this).text() == "Some oranges"; 
}).attr("selected", "selected"); 

現場小提琴:http://jsfiddle.net/WAsLu/

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

+0

以防萬一我添加了案例不敏感的衍生物 – 2011-12-29 14:10:37

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; 
};