如何选择 html <选项>其中 text=Washington

How to select html <option> where text=Washington

本文关键字:选项 其中 text Washington 何选择 选择 html      更新时间:2023-09-26

如何选择html,其中text=Washington我这样做就像

var opt = $("#address_states_state option[text='Washington']");
var html = $("<div>").append(opt.clone()).html();
html = html.replace(/'>/, ' selected="selected">');
opt.replaceWith(html);

没有直接的选择器来获取其text等于 X 的元素。不过,您可以做几件事:

您可以使用filter()

$('#address_states_state option').filter(function(i, el) {
   return $(el).text() === 'Washington'
});

或者,编写自己的伪选择器:

jQuery.expr[':'].textEquals = $.expr.createPseudo(function( text ) {
    return function(elem) {
        return $(elem).text() === text;
    }
});

然后你只需要做:

$('#address_states_state option:textEquals("Washington")')

这是后者的一个例子

您可以使用

:contains()选择器执行此操作:

$("#address_states_state option:contains('Washington')").prop('selected', true);

而不是执行克隆,然后将其替换为选定的选项。

演示 : 小提琴

更新

如果要选择具有特定文本的选项(在您的情况下为"华盛顿"),则可以执行以下操作:

$('#address_states_state option').filter(function () {
    return $(this).text().toLowerCase() === 'washington';
}).prop('selected', true);

演示 : 小提琴

相关文章: