javascript - "e.value"与 "e.options[e.selectedIndex].value"选择元素的值

标签 javascript html html-select selectedvalue selectedindex

给定 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.valuee.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 接口(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 an onchange 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 selected OPTION.

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

这已在以下定义中修复。

你可以在这里看到它的定义:

所以我认为它可以安全使用。

关于javascript - "e.value"与 "e.options[e.selectedIndex].value"选择元素的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25249961/

相关文章:

javascript - 隐藏 select2 多搜索框

php - 使用数据库结果填充第一个下拉菜单,并使用第一个下拉菜单值填充第二个

javascript - 谷歌脚本: Function to tally votes

javascript - 如何使用 Promises 递归迭代文件的树结构以获取?

javascript - 从 Word 插入文本时替换 html 标签

javascript - 如何创建流畅的滚动效果?

javascript - 根据另一个下拉列表的所选项目更改下拉所选项目

javascript - javascript中的小数点四舍五入

php - 从 URL 获取 div 的内容

html - 新行中第一个和最后一个内联 block 元素的选择器