jQuery :contains selector alternative? [duplicate]

2019-07-10 22:14发布

This question already has an answer here:

I would like to select an option in a drop down menu by its' text. When I run the code,:

var theText = "Large"; $("#size option:contains(" + theText + ")").attr('selected', 'selected');

it selects XLarge instead of Large. Is there any way to make it select Large? JSFiddle: http://jsfiddle.net/r8wuP/2/

3条回答
啃猪蹄的小仙女
2楼-- · 2019-07-10 22:26

You can use .filter() to find an exact match, :contains-selector returns partial matches also

var theText = "Large";
$("#size option").filter(function () {
    return $.trim($(this).text()) == theText;
}).attr('selected', 'selected');

Demo: Fiddle

查看更多
SAY GOODBYE
3楼-- · 2019-07-10 22:32

Try this:

http://jsfiddle.net/r8wuP/3/

$('#size').find('option').filter(function() {
    return $(this).text() === 'Large';
}).first().attr('selected', 'selected');
查看更多
趁早两清
4楼-- · 2019-07-10 22:33

Since you're using 1.4 this would work:

var theText = "Large";
$("#size").find("option[text='" + theText + "']").attr('selected', 'selected');

However later jQuery versions might need the filter method.

查看更多
登录 后发表回答