javascript – 具有“e.value”vs“e.options [e.selectedIndex] .value”的select元素的值

鉴于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');

要获得select的值,我可以使用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?

jsFiddle

解决方法:

HTMLSelectElement接口至少包括自1998年以来的文档对象模型(DOM)级别1规范以来的值属性.

但是,就像在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. (07001)

  • “Each control has both an initial value and a current value, both of
    which are character strings” (07002)

  • And SELECT may have an onchange attribute which implies a value.
    (07003)

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 selected
OPTION.

(…) Probably wouldn’t be a problem if HTML4.01 had been more explicit.

这在以下定义中得到修复.

你可以在这里看到它:

> HTMLSelectElement value DOM Level 1,W3C Recommendation,1998年10月1日

The current form control value.

> HTMLSelectElement value DOM Level 2,W3C Recommendation,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.

> HTMLSelectElementvalue,HTML5,W3C候选推荐

The value IDL attribute, on getting, must return the 070012 of the
first 070013 element in the 070014 in 070015 that has its
070016 set to true, if any. If there isn’t one, then it must
return the empty string.

所以我认为使用它是安全的.

上一篇:c# – 在ListView中选择下一项


下一篇:HBase启动时有进程webUI不显示HRegionServer各种情况解决方案