jquery选中select的option
jQuery 选中 select 的 option 方法
通过 value 选中 option
使用 val() 方法可以直接设置 select 的值,jQuery 会自动匹配对应的 option 并选中。
$('#mySelect').val('optionValue');
通过索引选中 option
使用 prop() 方法设置 selectedIndex 属性,可以通过索引选中 option。
$('#mySelect').prop('selectedIndex', 2); // 选中第三个 option
通过 text 选中 option
使用 filter() 方法筛选 option 的 text 内容,再设置 selected 属性。
$('#mySelect option').filter(function() {
return $(this).text() === 'Option Text';
}).prop('selected', true);
选中多个 option(适用于 multiple select)
对于多选 select,可以传递一个数组给 val() 方法。
$('#myMultiSelect').val(['value1', 'value2']);
动态添加 option 并选中
先添加 option 到 select 中,再设置选中状态。
$('#mySelect').append($('<option>', {
value: 'newValue',
text: 'New Option'
}));
$('#mySelect').val('newValue');
注意事项

- 确保 DOM 加载完成后再执行 jQuery 代码,可以将代码放在
$(document).ready()中。 - 对于动态加载的 select,可能需要使用事件委托或回调函数来确保操作时机正确。
- 某些老式浏览器可能需要使用
attr()代替prop(),但 jQuery 1.6+ 推荐使用prop()处理 selected 属性。
以上方法涵盖了 jQuery 操作 select 元素的常见需求,可以根据具体场景选择合适的方式。






