给定 HTML:
<select id="mySelect">
<option value="1">test1</option>
<option value="2">test2</option>
<option value="3">test3</option>
</select>
和javascript:
var e = document.getElementById('mySelect');
要获取选择的值,我可以使用 e.value
和 e.options[e.selectedIndex].value
。
我知道 e.options[e.selectedIndex].value
会给我选择的值(1,2 或 3)和 e.options[e.selectedIndex]。 text
会根据选择的内容给我 test1、test2、test3。
可以只使用 e.value
吗?这是旧浏览器的问题吗?
哪个更正确:e.value
vs e.options[e.selectedIndex].value
?
最佳答案
HTMLSelectElement
接口(interface)包含 value
属性,至少自 1998 年起,Document Object Model (DOM) Level 1 Specification 就包含了。
但是,就像this w3c mailing list中解释的那样,问题是 HTML4.01 规范含糊不清:
It's true that HTML4.01 doesn't explicitly specify a value attribute for SELECT, but it does seem to be implied:
'Menu' is a control type. (HTML4.01 17.2.1)
"Each control has both an initial value and a current value, both of which are character strings" (HTML4.01 17.2)
And
SELECT
may have anonchange
attribute which implies a value. (HTML4.01 17.6)But there's no mention of what the value represents, nor of what the initial or default values might be.
However, checking in IE5 and Mozilla, the value of
SELECT
does indeed return a string corresponding to the value of the currently selectedOPTION
.(...) Probably wouldn't be a problem if HTML4.01 had been more explicit.
这已在以下定义中修复。
你可以在这里看到它的定义:
HTMLSelectElement
的value
在 DOM Level 1 , W3C 推荐标准,1998 年 10 月 1 日The current form control value.
HTMLSelectElement
的value
在 DOM Level 2 , W3C 推荐标准,2003 年 1 月 9 日The current form control value (i.e. the value of the currently selected option), if multiple options are selected this is the value of the first selected option.
HTMLSelectElement
的value
在 HTML5 中,W3C 候选推荐The
value
IDL attribute, on getting, must return the value of the firstoption
element in the list of options in tree order that has its selectedness set to true, if any. If there isn't one, then it must return the empty string.
所以我认为它可以安全使用。
关于javascript - "e.value"与 "e.options[e.selectedIndex].value"选择元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249961/