- 如果 select 元素下的所有 option 元素均没有指定 selected 属性,会默认选中第一个。
- 可以通过
select.selectedIndex获取到选中的 option 元素的索引。 - 可以通过
select.options[select.selectedIndex]获取到选中的 option 元素。 - option 元素
<option selected="selected" value="value3">text3</option>,可以通过 option.value 获得 option 元素的 value 属性值,即 value3;可以通过 option.text 获得 option 元素内的文本,即 text3。 - 如果 option 元素没有定义 value 属性,则 IE 中 option.value 无法获得,但 Safari、Opera、FireFox 依旧可以通过 option.value 获得,值同于 option.text 。
- 可以通过
option.attributes.value && option.attributes.value.specified来判断 option 元素是否定义了 value 属性。
故,获得当前 select 元素值的脚本如下:
var getSelectValue = function(select) {
var idx = select.selectedIndex,
option,
value;
if (idx > -1) {
option = select.options[idx];
value = option.attributes.value;
return (value && value.specified) ? option.value : option.text;
}
return null;
}


共有15 条评论
我一直是直接使用select.value来获取select的选中值。
$(‘selectId’).value 不就是selcet选中的option的值么
为什么还需要用select.options[idx].attributes.value ?
IE下有个烦人的问题: console.log(document.getElementById(“test”).value);
在IE下无法得到value的值,把value改成其它名称如init_value就可以获得。
评论系统把html直接过滤了?
@vapour and rs 对于value值可以通过select.value 取得的,但对于text值则需要通过select.options[select.sekectedIndex].txet 获得。
以前由于兼容性问题,大家用select.options[select.sekectedIndex].value来取值,不过现在用select.value都可以了
option.attributes.value.specified
这个以前不知道,学习了,嗯。。
很实用!
function 不是funtion
return (value && value.specified) ? option.value : option.text);
后面的括号没有用。。语法错误,嗯。。
@simaopig 谢谢,已修正,笔误
还得考虑 multiple select, 整理了一段代码:
http://kissy.googlecode.com/svn/trunk/src/dom/dom.js
搜索 val 方法的实现
测试页面:
http://kissy.googlecode.com/svn/trunk/src/dom/test-dom.html
我最近也碰到了Select的问题,http://adamlu.com/?p=361 哈哈
[...] 原文:需要點這裡… [...]
这个现在都不能用了,ff新版本不好用了
请问为什么还有判断value.specified呢?