[英]jquery set selected attribute on an option using like
如何設置從以下選擇框中選擇的ubuntu我嘗試了以下內容
<select>
<option value="val1">Val 1</option>
<option value="val2">Val 2</option>
<option value="val3">Val 3</option>
<option value="val3">Ubuntu -12.04 amd......</option>
</select>
$('#image_id').find('option[text="ubuntu"]').attr('selected');
我假設你的select
id值為image_id
:
<select id="image_id">
然后你可以使用:contains()選擇器:
$('#image_id').find('option:contains("Ubuntu")').prop('selected',true);
注意:: :contains
是區分大小寫的,如果你想匹配ubuntu
,你需要覆蓋默認的:contains()
方法:
$.expr[":"].contains = $.expr.createPseudo(function(arg) {
return function( elem ) {
return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
};
});
我喜歡使用.filter來獲得對查找過程的更多控制:
// Use the function overload for val
$("#image_id").val(function() {
// Find the value of the option inside which matches the criteria
return $(this).find("option").filter(function() {
var text = $(this).text().toLowerCase();
// Do a case-insensitive search for both "ubuntu" and "12.04"
return text.indexOf("ubuntu") > -1 && text.indexOf("12.04") > -1;
}).val();
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.