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

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

有选择器来做这个吗?

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


当前回答

下面的jquery 1.10.2版本适合我

  var selectedText="YourMatchText";
    $('#YourDropdownId option').map(function () {
       if ($(this).text() == selectedText) return this;
      }).attr('selected', 'selected');
    });

其他回答

这是我在jquery V3.6.0的工作在2022年

$("#select >option").filter( function()
{
    if ($(this).text() === "123")
    {
        $(this).prop("selected", true);
    }
});

这可能会有所帮助:

$('#test').find('option[text="B"]').val();

演示小提琴

这将为你提供带有文本B的选项,而不是包含文本B的选项。

对于最新版本的jQuery,上述问题无法解决。正如下面Quandary所评论的,这是jQuery 1.9.1的工作原理:

$('#test option').filter(function () { return $(this).html() == "B"; }).val();

更新的小提琴

这对我来说很管用:

var result = $('#SubjectID option')
            .filter(function () 
             { return $(this).html() == "English"; }).val();

result变量将返回匹配文本值的索引。现在我将使用它的索引来设置它:

$('#SubjectID').val(result);

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);

如回答中所述,您可以轻松地为hasText创建自己的选择器。这允许你找到$('#test').find('option:hastText("B")').val();

下面是我添加的hasText方法:

 if( ! $.expr[':']['hasText'] ) {
     $.expr[':']['hasText'] = function( node, index, props ) {
       var retVal = false;
       // Verify single text child node with matching text
       if( node.nodeType == 1 && node.childNodes.length == 1 ) {
         var childNode = node.childNodes[0];
         retVal = childNode.nodeType == 3 && childNode.nodeValue === props[3];
       }
       return retVal;
     };
  }