jQuery :contains selector alternative? [duplicate]

2019-07-10 21:44发布

问题:

This question already has an answer here:

  • JQuery :contains function limit to exact match 3 answers

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/

回答1:

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



回答2:

Try this:

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

$('#size').find('option').filter(function() {
    return $(this).text() === 'Large';
}).first().attr('selected', 'selected');


回答3:

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.