ICode9

精准搜索请尝试: 精确搜索
首页 > 编程语言> 文章详细

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

2019-07-22 20:36:09  阅读:332  来源: 互联网

标签:html selectedindex javascript html-select selectedvalue


鉴于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.

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

标签:html,selectedindex,javascript,html-select,selectedvalue
来源: https://codeday.me/bug/20190722/1506330.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有