简体   繁体   English

jquery使用like设置选项的选定属性

[英]jquery set selected attribute on an option using like

How can i set ubuntu selected from the following select box i tried the following below 如何设置从以下选择框中选择的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');

I assume that your select has id value as image_id : 我假设你的select id值为image_id

<select id="image_id">

then you can use :contains() selector: 然后你可以使用:contains()选择器:

$('#image_id').find('option:contains("Ubuntu")').prop('selected',true);

Note: :contains is case-sensitive , if you want to match ubuntu as well than you need to override the default :contains() method: 注意:: :contains是区分大小写的,如果你想匹配ubuntu ,你需要覆盖默认的:contains()方法:

$.expr[":"].contains = $.expr.createPseudo(function(arg) {
    return function( elem ) {
        return $(elem).text().toUpperCase().indexOf(arg.toUpperCase()) >= 0;
    };
}); 

Fiddle Demo 小提琴演示

Try, 尝试,

$('#image_id').find('option:contains("Ubuntu -12.04")').prop('selected',true);

Working Demo 工作演示

So as per your new request you can do like, 所以根据您的新要求,您可以这样做,

$('#image_id').find('option:contains("Ubuntu"):contains("-12.04")').prop('selected',true);

Working Demo 工作演示

I like to use .filter to gain more control over the finding process: 我喜欢使用.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();
});

jsFiddle 的jsfiddle

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM