HTMLSelectElement: selectedIndex 属性
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 |
浏览器兼容性
加载中…