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

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

有选择器来做这个吗?

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


当前回答

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

这对我很有用

var options = $(dropdown).find('option');
var targetOption = $(options).filter(
function () { return $(this).html() == value; });

console.log($(targetOption).val());

谢谢你的帖子。

这对我有用:$(“#test”).find(“选项:contains('abc')”);

这是在下拉列表中选择文本的最佳方法。

$("#dropdownid option:contains(your selected text)").attr('selected', true);