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

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

有选择器来做这个吗?

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


当前回答

使用以下

$('#select option:contains(ABC)').val();

其他回答

这也是可行的。

$(" #测试”)。找到(“选择选项:包含(B)”).filter(":选择");

如回答中所述,您可以轻松地为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;
     };
  }

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

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

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

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

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

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

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

这对我很有用

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

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

谢谢你的帖子。