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值改变后,初始化的值是不会变的。

你可能感兴趣的:(select)