通过JQuery选择选择中的选项

问题描述:

我可以选择以下选项:

<select>
     <option value="1">A</option>
     <option value="2">B</option>
     <option value="3">C</option>
</select>

我不知道值是什么,但是在我的JQuery代码中,我想选择选项二,因为我知道文本是B(但无其他内容).

I don't know what the values are, but in my JQuery code, I want to select option two because I know that the text is B (but nothing else).

怎么办?

您可以使用 :contains() 选择器:

You can use the :contains() selector:

$('option:contains("B")').prop('selected', true);

或者:

$('option')
    .filter(function() {
        return this.text == 'B'; 
    })
    .prop('selected', true);