我需要检查<select>是否有一个文本等于特定值的选项。
例如,如果有一个<option value="123">abc</option>,我将寻找"abc"。
有选择器来做这个吗?
我在寻找类似于$('#选择选项[值="123"]');除了文本。
我需要检查<select>是否有一个文本等于特定值的选项。
例如,如果有一个<option value="123">abc</option>,我将寻找"abc"。
有选择器来做这个吗?
我在寻找类似于$('#选择选项[值="123"]');除了文本。
当前回答
那是10年前的事了。 现在jquery是EOL,我们可以使用普通的DOM来完成这个简单的工作
document.getElementById("SomeSelectId").querySelectorAll("option").forEach(o => o.selected = o.innerText == text);
其他回答
如回答中所述,您可以轻松地为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;
};
}
这是在下拉列表中选择文本的最佳方法。
$("#dropdownid option:contains(your selected text)").attr('selected', true);
这对我来说很管用:
var result = $('#SubjectID option')
.filter(function ()
{ return $(this).html() == "English"; }).val();
result变量将返回匹配文本值的索引。现在我将使用它的索引来设置它:
$('#SubjectID').val(result);
这对我有用:$(“#test”).find(“选项:contains('abc')”);
这是我在jquery V3.6.0的工作在2022年
$("#select >option").filter( function()
{
if ($(this).text() === "123")
{
$(this).prop("selected", true);
}
});