HTMLSelectElement: selectedIndex 属性

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

selectedIndex 属性是 HTMLSelectElement 接口的一个属性,它表示一个 <select> 元素中第一个被选中的 <option> 元素的数值索引,如果没有被选中的项,则返回 −1。设置此属性会选中指定索引处的选项并取消选中所有其他选项;将其设置为 -1 会取消选中任何当前选中的选项。

一个数字。

示例

HTML

html
<p id="p">selectedIndex: 0</p>

<select id="select">
  <option selected>Option A</option>
  <option>Option B</option>
  <option>Option C</option>
  <option>Option D</option>
  <option>Option E</option>
</select>

JavaScript

js
const selectElem = document.getElementById("select");
const pElem = document.getElementById("p");

// When a new <option> is selected
selectElem.addEventListener("change", () => {
  const index = selectElem.selectedIndex;
  // Add that data to the <p>
  pElem.textContent = `selectedIndex: ${index}`;
});

规范

规范
HTML
# dom-select-selectedindex-dev

浏览器兼容性

另见