--- title: HTMLSelectElement.selectedIndex slug: Web/API/HTMLSelectElement/selectedIndex tags: - API - HTML DOM - HTMLSelectElement - HTML表单 - 参考 - 属性 translation_of: Web/API/HTMLSelectElement/selectedIndex ---
HTMLSelectElement.selectedIndex 是一个长整型数,它反映了被选中的第一个 {{HTMLElement("option")}} 元素的索引值。值为-1时表明没有元素被选中。
var index = selectElem.selectedIndex;
selectElem.selectedIndex = index;
<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>
var selectElem = document.getElementById('select')
var pElem = document.getElementById('p')
// 当有新的<option>元素被选中时
selectElem.addEventListener('change', function() {
var index = selectElem.selectedIndex;
// 把index数据添加到p元素中
pElem.innerHTML = 'selectedIndex: ' + index;
})
{{EmbedLiveSample("Example", "200px", "80px")}}
| 规范 | 状态 | 注释 |
|---|---|---|
| {{SpecName('HTML WHATWG', '#dom-select-selectedindex', 'HTMLSelectElement')}} | {{Spec2('HTML WHATWG')}} | No change since the latest snapshot, {{SpecName("HTML5 W3C")}}. |
| {{SpecName('HTML5 W3C', 'forms.html#dom-select-selectedindex', 'HTMLSelectElement')}} | {{Spec2('HTML5 W3C')}} | Initial definition, snapshot of {{SpecName("HTML WHATWG")}}. |
{{Compat("api.HTMLSelectElement.selectedIndex")}}