【问题标题】:How to set multiple selectedIndexes without jQuery?如何在没有 jQuery 的情况下设置多个 selectedIndexes?
【发布时间】: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>

这是设置选定选项onethreefive 的最有效方法吗? 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


【解决方案1】:

循环您的索引数组并更新与索引匹配的options

const select = document.getElementById('sel');
const indexes = [0, 2, 4];
// Clear the default selected
select.selectedIndex = -1;
// Select those indexes you want
for(var idx of indexes){
  select[idx].selected = true
}
<select id="sel" multiple size=5>
  <option>one</option>
  <option>two</option>
  <option>three</option>
  <option selected>four</option>
  <option>five</option>
</select>

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 2015-09-20
  • 1970-01-01
  • 2014-01-07
  • 2014-09-15
  • 1970-01-01
相关资源
最近更新 更多