我需要检查<select>是否有一个文本等于特定值的选项。

例如,如果有一个<option value="123">abc</option>,我将寻找"abc"。

有选择器来做这个吗?

我在寻找类似于$('#选择选项[值="123"]');除了文本。


当前回答

使用prop而不是attr

$('#mySelect option:contains(' + value + ')').each(function(){
    if ($(this).text() == value) {
        $(this).prop('selected', 'selected');
        return false;
    }
    return true;
});

其他回答

2022年8月25日。

对于jQuery v3.5.1,真正对我有用的是:

$('#selectID option:contains("label")').prop('selected', true);

如果你在一个变量中有文本,这样做:

  ddText = 'Text to find';
  $('#selectID option:contains("' + ddText + '")').prop('selected', true);

之前的建议在jQuery 1.7.2中都不适用,因为我试图根据文本框中的值设置列表的选定索引,而一些文本值包含在多个选项中。我最终使用了以下方法:

$('#mySelect option:contains(' + value + ')').each(function(){
    if ($(this).text() == value) {
        $(this).attr('selected', 'selected');
        return false;
    }
    return true;
});

您可以使用:contains()选择器来选择包含特定文本的元素。 例如:

$('#mySelect option:contains(abc)')

要检查给定的<select>元素是否有这样的选项,使用.has()方法:

if (mySelect.has('option:contains(abc)').length)

要查找所有包含此选项的<select>,请使用:has()选择器:

$('select:has(option:contains(abc))')

您可以遍历选项,也可以将相同的文本放在选项的另一个属性中并使用该属性进行选择。

我遇到了同样的问题,下面是工作代码:

$("#test option").filter(function() {
    return $(this).text() =='Ford';
}).prop("selected", true);

演示:http://jsfiddle.net/YRBrp/83/