分享

如何获取当前 select 元素的值

 xiaozhenyu 2013-08-09
如何获取当前 select 元素的值

作者:blank 时间: 2010-03-29 文档类型:原创 来自:蓝色理想

  1. 如果 select 元素下的所有 option 元素均没有指定 selected 属性,会默认选中第一个。
  2. 可以通过 select.selectedIndex 获取到选中的 option 元素的索引。
  3. 可以通过 select.options[select.selectedIndex] 获取到选中的 option 元素。
  4. option 元素 <option selected="selected" value="value3">text3</option>,可以通过 option.value 获得 option 元素的 value 属性值,即 value3;可以通过 option.text 获得 option 元素内的文本,即 text3。
  5. 如果 option 元素没有定义 value 属性,则 IE 中 option.value 无法获得,但 Safari、Opera、FireFox 依旧可以通过 option.value 获得,值同于 option.text 。
  6. 可以通过 option.attributes.value && option.attributes.value.specified 来判断 option 元素是否定义了 value 属性。

故,获得当前 select 元素值的脚本如下:

var getSelectValue = funtion(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;
}

    本站是提供个人知识管理的网络存储空间,所有内容均由用户发布,不代表本站观点。请注意甄别内容中的联系方式、诱导购买等信息,谨防诈骗。如发现有害或侵权内容,请点击一键举报。
    转藏 分享 献花(0

    0条评论

    发表

    请遵守用户 评论公约

    类似文章 更多