jQuery:包含选择器替代?

时间:2014-03-08 16:44:22

标签: javascript jquery drop-down-menu

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

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

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

3 个答案:

答案 0 :(得分:4)

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

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

演示:Fiddle

答案 1 :(得分:0)

试试这个:

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

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

答案 2 :(得分:0)

由于您使用1.4,这将起作用:

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

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

相关问题