How do I select an item by its text value in a dropdown using jQuery?

如果我有以下选择,并且不知道用于像这个问题那样事先选择一个项目的值或者我想要选择的项目的索引,那么如果我确实知道这个选项,我怎么才能用jQuery选择一个选项文本值像选项C?

<select id='list'>
<option value='45'>Option A</option>
<option value='23'>Option B</option>
<option value='17'>Option C</option>
</select>

var option;
$('#list option').each(function() {
    if($(this).text() == 'Option C') {
        option = this;
        return false;
    }
});

This should do the trick:

// option text to search for
var optText = "Option B";
// find option value that corresponds
var optVal = $("#list option:contains('"+optText+"')").attr('value');
// select the option value 
$("#list").val( optVal )

As eyelidlessness points out, this will behave unpredictably when the text being searched for can be found in more than one option.


$("#list option").each(function() {
  this.selected = $(this).text() == "Option C";
});
链接地址: http://www.djcxy.com/p/83072.html

上一篇: JQuery检索文本而不是选择列表的值

下一篇: 如何使用jQuery在下拉菜单中通过文本值选择项目?