在 html `
当
以下代码可安全、高效地选中值为 "
0"、"2" 和 "4" 的选项:
const targetValues = ['0', '2', '4'];
targetValues.forEach(value => {
const option = document.querySelector(`#weekday option[value="${value}"]`);
if (option) option.selected = true;
});? 说明:使用 #weekday option[value="..."] 限定作用域(避免跨 select 冲突),并添加 if (option) 防御性检查,防止因值不存在导致报错。
const selectedValues = Array.from(
document.querySelectorAll('#weekday option:checked')
).map(opt => opt.value);
// 或更兼容的写法:
// const selectedValues = [...document.querySelectorAll('#weekday option')].filter(o => o.selected).map(o => o.value);function selectOptions(selectId, values) {
const select = document.getElementById(selectId);
if (!select) return;
Array.from(select.options).forEach(option => {
option.selected = values.includes(option.value);
});
}
// 使用示例:
selectOptions('weekday', ['0', '2', '4']);该函数支持精确匹配与批量控制,兼顾可读性与健壮性,适用于各类多选场景。