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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM