jQuery:包含选择器替代?

我想通过’文本在下拉菜单中选择一个选项。 当我运行代码时,:

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

它选择XLarge而不是Large。 有没有办法让它选择大? JSFiddle: http : //jsfiddle.net/r8wuP/2/

您可以使用.filter()来查找完全匹配, :contains-selector也返回部分匹配

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

演示: 小提琴

试试这个:

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

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

既然你使用1.4就可以了:

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

但是后来的jQuery版本可能需要filter方法。