zoukankan      html  css  js  c++  java
  • js获取select默认选中的Option (非当前选中值)

    js函数方法:

     1   <script>
     2     function getDefaultSelectedOption(selectId, valIfNull) {
     3       var selectId = selectId.replace(/^#/, ''), opts;
     4       try {
     5         opts = document.getElementById(selectId).getElementsByTagName('option');
     6         for (var i in opts) {
     7           if (opts[i].defaultSelected) {
     8            return opts[i];
     9            }
    11         }
    12       } catch (e) {
    13       }
    14       return valIfNull;
    15     }
    16   </script>

    Demo:

     1 <body>
     2   <select id="sel">
     3     <option value="1">1</option>
     4     <option value="2" selected="">2</option>
     5     <option value="3">3</option>
     6   </select>
     7   <button id="btn">test</button>
     8   <script>
     9     function getDefaultSelectedOption(selectId, valIfNull) {
    10       var  selectId = selectId.replace(/^#/, ''), opts;
    11       try {
    12         opts = document.getElementById(selectId).getElementsByTagName('option');
    13         for (var i in opts) {
    14           if (opts[i].defaultSelected) {
    15             return opts[i];
    16             }
    18         }
    19       } catch (e) {
    20       }
    21       return valIfNull;
    22     }
    23   </script>
    24   <script>
    25     document.getElementById('btn').onclick = function () {
    26       alert((getDefaultSelectedOption('sel', {})).value);
    27     };
    28   </script>
    29 </body>

    不知道还有没有更方便快捷的方法,曾尝试通过jQuery获取$('#sel option[defaultSelected]'),可一直返回空。

    各位园友,我要的是select控件初始化的值,非select当前选中的值,初始化的值不随select值改变,大家可以做一下Demo,当select值改变后,初始化的值是不会变的。

  • 相关阅读:
    P3387 【模板】缩点 tarjan
    P2831 愤怒的小鸟 状压dp
    交流帖
    P3959 宝藏 模拟退火。。。
    B1060 [ZJOI2007]时态同步 dfs
    P1850 换教室 概率dp
    树链刨分(待修改)
    B3403 [Usaco2009 Open]Cow Line 直线上的牛 deque
    B3402 [Usaco2009 Open]Hide and Seek 捉迷藏 最短路
    B5248 [2018多省省队联测]一双木棋 状压dp
  • 原文地址:https://www.cnblogs.com/lizhanglong/p/3711953.html
Copyright © 2011-2022 走看看