html select用法总结

本文将介绍select 原生的常用方法,这些都是经过测试,兼容ie6到ie10,及chrome,火狐等,也就是说大部分浏览器都兼容。如果大家发现有不兼容的情况,可以跟我留言。

我们对基本的用法了如指掌后,jQuery、kissy这些框架用起来更方便。

 1 <!DOCTYPE html>
 2 <html>
 3 <head>
 4     <meta charset="utf-8" />
 5     <title>select用法总结</title>
 6 </head>
 7 <body>
 8 <h3>select的常用方法</h3>
 9 <hr/>
10 
11 
12 <div>
13     <h3>默认选中某一项,使用option的selected属性</h3>
14     <select name="test" id="test1">
15         <option value="1">1</option>
16         <option value="2" selected>2</option>
17         <option value="3">3</option>
18     </select>
19 </div>
20 
21 
22 <div>
23     <h3>js使某一项选中</h3>
24     <select name="test" id="test2">
25         <option value="1">1</option>
26         <option value="2">2</option>
27         <option value="3">3</option>
28     </select>
29     <script>
30         var test2 = document.getElementById('test2');
31         test2.value='3';
32         //kissy用法
33         //S.one('#test2').val('3');
34     </script>
35 </div>
36 
37 <div>
38     <h3>事件绑定,获取选中项的值</h3>
39     <select name="test" id="test3">
40         <option value="1">1</option>
41         <option value="2">2</option>
42         <option value="3">3</option>
43     </select>
44     <script>
45         var test3 = document.getElementById('test3');
46         test3.onchange = function(e){
47             //经常看到有的代码这样写this.options[this.selectedIndex].value
48             //其实不用那么复杂,this.value就可以取到当前选中项的值,所有浏览器都支持
49             var val = this.value; //var val = test3.value;
50             alert(val);
51         }
52     </script>
53 </div>
54 
55 <div>
56     <h3>获取选中项的index</h3>
57     <select name="test" id="test4">
58         <option value="1">1</option>
59         <option value="2">2</option>
60         <option value="3">3</option>
61     </select>
62     <script>
63         var test4 = document.getElementById('test4');
64         test4.onchange = function(e){
65             var idx = this.selectedIndex; //从0开始
66             alert(idx);
67         }
68     </script>
69 </div>
70 <div>
71     <h3>获取选中项的text</h3>
72     <select name="test" id="test5">
73         <option value="1">text1</option>
74         <option value="2">text2</option>
75         <option value="3">text3</option>
76     </select>
77     <script>
78         var test5 = document.getElementById('test5');
79         test5.onchange = function(e){
80             var selOption = this.options[this.selectedIndex]; //var val = test3.value;
81             // ie,chrome 下调用 innerText 其他浏览器如firefox下调用 textContent
82             var text = selOption.innerText || selOption.textContent; //兼容性
83             //所有浏览器都支持w3c标准的innerHTML,如果text里有标签可以通过正则替换
84             var html = selOption.innerHTML;
85             alert(text);
86             alert(html);
87         }
88     </script>
89 </div>
90 
91 </body>
92 </html>

 代码地址:http://jsfiddle.net/6o1fdvm0/ 大家可以在这里测试

原文地址:https://www.cnblogs.com/summer_shao/p/select.html