aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/api/htmlselectelement/selectedindex/index.html
blob: 90217f241b2fa2132b5c6d32431b960b386570ae (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
---
title: HTMLSelectElement.selectedIndex
slug: Web/API/HTMLSelectElement/selectedIndex
tags:
  - API
  - HTML DOM
  - HTMLSelectElement
  - HTML表单
  - 参考
  - 属性
translation_of: Web/API/HTMLSelectElement/selectedIndex
---
<div>{{APIRef("HTML DOM")}}</div>

<p><code><strong>HTMLSelectElement.selectedIndex</strong></code> 是一个长整型数,它反映了被选中的第一个 {{HTMLElement("option")}} 元素的索引值。值为-1时表明没有元素被选中。</p>

<h2 id="语法">语法</h2>

<pre class="syntaxbox">var <var>index</var> = <var>selectElem</var>.selectedIndex;
<em>selectElem<code>.selectedIndex = </code>index;</em>
</pre>

<h2 id="示例">示例</h2>

<h3 id="HTML">HTML</h3>

<pre class="brush: html">&lt;p id="p"&gt;selectedIndex: 0&lt;/p&gt;

&lt;select id="select"&gt;
  &lt;option selected&gt;Option A&lt;/option&gt;
  &lt;option&gt;Option B&lt;/option&gt;
  &lt;option&gt;Option C&lt;/option&gt;
  &lt;option&gt;Option D&lt;/option&gt;
  &lt;option&gt;Option E&lt;/option&gt;
&lt;/select&gt;
</pre>

<h3 id="JavaScript">JavaScript</h3>

<pre class="brush: js; highlight[6]">var selectElem = document.getElementById('select')
var pElem = document.getElementById('p')

// 当有新的&lt;option&gt;元素被选中时
selectElem.addEventListener('change', function() {
  var index = selectElem.selectedIndex;
  // 把index数据添加到p元素中
  pElem.innerHTML = 'selectedIndex: ' + index;
})</pre>

<p><iframe class="live-sample-frame sample-code-frame" frameborder="0" height="80px" id="frame_Example" src="https://mdn.mozillademos.org/en-US/docs/Web/API/HTMLSelectElement/selectedIndex$samples/Example?revision=1546597" width="200px"></iframe></p>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <tbody>
  <tr>
   <th scope="col">规范</th>
   <th scope="col">状态</th>
   <th scope="col">注释</th>
  </tr>
  <tr>
   <td>{{SpecName('HTML WHATWG', '#dom-select-selectedindex', 'HTMLSelectElement')}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td>No change since the latest snapshot, {{SpecName("HTML5 W3C")}}.</td>
  </tr>
  <tr>
   <td>{{SpecName('HTML5 W3C', 'forms.html#dom-select-selectedindex', 'HTMLSelectElement')}}</td>
   <td>{{Spec2('HTML5 W3C')}}</td>
   <td>Initial definition, snapshot of {{SpecName("HTML WHATWG")}}.</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p>{{Compat("api.HTMLSelectElement.selectedIndex")}}</p>

<div></div>

<div id="compat-mobile"></div>