web开发中,经常需要给select动态添加数据,常用的方法有几种:
1.基于dom方式的添加
2.使用innerHTML添加
3.object方式添加
1 < html >
2 < head >
3 < script >
4
5 var city = new Array();
6 city[ 0 ] = " 西安 " ;
7 city[ 1 ] = " 乌鲁木齐 " ;
8 city[ 2 ] = " 西宁 " ;
9 city[ 3 ] = " 北京 " ;
10 function objectF()
11 {
12
13 var s = document.getElementById( " object " );
14 for (var i = 0 ;i < city.length;i ++ )
15 {
16 var option = new Option(city[i],i);
17 s.options[i] = option;
18
19 }
20 }
21 function domF()
22 {
23 var s = document.getElementById( " dom " );
24 for (var i = 0 ;i < city.length;i ++ )
25 {
26 var option = document.createElement( " option " );
27 var text = document.createTextNode(city[i]);
28 option.appendChild(text);
29 option.value = i;
30 s.appendChild(option);
31
32 }
33 }
34 function innerF()
35 {
36
37 var sel = document.getElementById( " inner " );
38 var str = " <select> " ;
39 for (var i = 0 ;i < city.length;i ++ )
40 {
41 strstr = str + " <option value=' " + i + " '> " + city[i] + " </option> "
42 }
43 strstr = str + " </select> " ;
44 sel.innerHTML = str;
45 }
46 </ script >
47 </ head >
48 < body >
49 < form >
50 < table >
51 < tr >
52 < td >
53 < select ></ select >
54 </ td >
55 < td >
56 < select ></ select >
57 </ td >
58 < td >
59 < div >
60 < select ></ select >
61 </ div >
62 </ td >
63 </ tr >
64 < tr >
65 < td >< input type = " button " value = " dom " ></ td >
66 < td >< input type = " button " value = " object " ></ td >
67 < td >< input type = " button " value = " inner " ></ td >
68 </ tr >
69 </ table >
70 </ body >
71
72
2 < head >
3 < script >
4
5 var city = new Array();
6 city[ 0 ] = " 西安 " ;
7 city[ 1 ] = " 乌鲁木齐 " ;
8 city[ 2 ] = " 西宁 " ;
9 city[ 3 ] = " 北京 " ;
10 function objectF()
11 {
12
13 var s = document.getElementById( " object " );
14 for (var i = 0 ;i < city.length;i ++ )
15 {
16 var option = new Option(city[i],i);
17 s.options[i] = option;
18
19 }
20 }
21 function domF()
22 {
23 var s = document.getElementById( " dom " );
24 for (var i = 0 ;i < city.length;i ++ )
25 {
26 var option = document.createElement( " option " );
27 var text = document.createTextNode(city[i]);
28 option.appendChild(text);
29 option.value = i;
30 s.appendChild(option);
31
32 }
33 }
34 function innerF()
35 {
36
37 var sel = document.getElementById( " inner " );
38 var str = " <select> " ;
39 for (var i = 0 ;i < city.length;i ++ )
40 {
41 strstr = str + " <option value=' " + i + " '> " + city[i] + " </option> "
42 }
43 strstr = str + " </select> " ;
44 sel.innerHTML = str;
45 }
46 </ script >
47 </ head >
48 < body >
49 < form >
50 < table >
51 < tr >
52 < td >
53 < select ></ select >
54 </ td >
55 < td >
56 < select ></ select >
57 </ td >
58 < td >
59 < div >
60 < select ></ select >
61 </ div >
62 </ td >
63 </ tr >
64 < tr >
65 < td >< input type = " button " value = " dom " ></ td >
66 < td >< input type = " button " value = " object " ></ td >
67 < td >< input type = " button " value = " inner " ></ td >
68 </ tr >
69 </ table >
70 </ body >
71
72