本文详解在 html `
当
以下是最简洁可靠的实现方式:
// 指定要选中的 value 数组(字符串形式)
const targetValues = ['0', '2', '4'];
// 获取 select 元素(推荐限定作用域,避免误选全局同 value 选项)
const selectEl = document.getElementById('weekday');
// 遍历目标值,逐一设置对应 option 的 selected 状态
targetValues.forEach(value => {
const option = selectEl.querySelector(`option[value="${value}"]`);
if (option) option.selected = true;
});✅ 优势说明:
⚠️ 重要注意事项:
),若页面存在多个多选框,可能误操作其他控件; Array.from(selectEl.options).forEach(opt => opt.selected = false);
此外,如需获取当前所有已选值,可使用:
const selectedValues = Array.from(selectEl.selectedOptions) .map(option => option.value); // 返回 ['0', '2', '4']
掌握这一模式,即可灵活应对表单初始化、条件联动、数据回填等典型场景,无需引入框架,纯原生、高性能、易维护。