新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

HTML Select selectedIndex的有哪些作用

发布时间:2023-10-19 10:38:10

HTML Select selectedIndex的有哪些作用

HTML Select的selectedIndex属性用于获得或设置select元素中被选当选项的索引。它可用于肯定被选当选项的索引,也能够设置特定选项为被选中状态。
以下是selectedIndex属性的几种用法:

  1. 获得被选当选项的索引:
const select = document.getElementById("mySelect");
const selectedIndex = select.selectedIndex;
console.log(selectedIndex);  // 输出被选当选项的索引
  1. 设置选项为被选中状态:
const select = document.getElementById("mySelect");
select.selectedIndex = 2;  // 将索引为2的选项设置为被选中状态

注意:设置selectedIndex属性时,如果指定的索引超越了可选项的范围,将不会有任何效果。

  1. 使用selectedIndex属性来获得或设置select元素中被选当选项的值:
const select = document.getElementById("mySelect");
const selectedValue = select.options[select.selectedIndex].value;  // 获得被选当选项的值
console.log(selectedValue);  // 输出被选当选项的值

总之,HTML Select的selectedIndex属性用于获得或设置被选当选项的索引,和通过索引设置特定选项为被选中状态。