【发布时间】:2018-04-15 13:23:42
【问题描述】:
我见过this question,但我的问题不同,因为另一个问题使用了value 和 jQuery,我都不想使用。
举个例子更容易解释:
const select = document.getElementById('sel');
const indexes = new Set([0, 2, 4]);
Array.prototype.forEach.call(select.options, (opt, i) => {
opt.selected = indexes.has(i);
});
<select id="sel" multiple size=5>
<option>one</option>
<option>two</option>
<option>three</option>
<option selected>four</option>
<option>five</option>
</select>
这是设置选定选项one、three 和five 的最有效方法吗? select.selectedIndex 似乎不接受数组,所以这是我能想到的唯一方法。使用Set 应该比遍历数组更有效,每次都使用.includes。
【问题讨论】:
-
selectedOptions包含选定选项元素的集合,但它是只读的。我认为你所拥有的可能是最好的方法。 -
但在您的示例中,您还取消选择了第四个选项。
-
我尝试了一些事情,使用循环似乎大约 0.1 毫秒或更多,设置
select.innerHTML大约 0.05 毫秒,设置它们没有循环select.selectedIndex = 0; select[2].selected = true; select[4].selected = true大约 0.03 毫秒。哈!具有讽刺意味的是,标记为重复是最in最有效的多选方式 -
这是一个关于按值(而不是索引)选择多个选项的非常相似的问题:stackoverflow.com/questions/16582901/…
标签: javascript html