huxiuliang 发表于 2013-2-7 21:00:38

动态给select添加选项的常用方法


[*]<html>  
[*]<head>  
[*]<script>  
[*]  
[*]  
[*] var city = new Array();  
[*] city="西安";  
[*] city="乌鲁木齐";  
[*] city="西宁";  
[*] city="北京";  
[*] function objectF()  
[*] {  
[*] 
[*]  //object方式添加
[*]  var s = document.getElementById("object");  
[*]  for(var i=0;i<city.length;i++)  
[*]  {  
[*]   var option = new Option(city,i);  
[*]   s.options=option;  
[*]     
[*]  }  
[*] }  
[*] function domF()  
[*] { 
[*] //基于dom方式的添加
[*]  var s = document.getElementById("dom");  
[*]  for (var i=0;i<city.length;i++)  
[*]  {  
[*]   var option = document.createElement("option");  
[*]   var text = document.createTextNode(city);  
[*]   option.appendChild(text);  
[*]   option.value=i;  
[*]   s.appendChild(option);  
[*]    
[*]  }  
[*] }  
[*] function innerF()  
[*] {  
[*] 
[*]//使用innerHTML添加 在ie中有时会出错
[*]  var sel = document.getElementById("inner");  
[*]  var str = "<select>";  
[*]  for (var i=0;i<city.length;i++)  
[*]  {  
[*]   str = str + "<option value='"+i+"'>"+city+"</option>"  
[*]  }  
[*]  str=str+"</select>";  
[*]  sel.innerHTML=str;  
[*] }  
[*]</script>  
[*]</head>  
[*]<body>  
[*]<form>  
[*]<table>  
[*] <tr>  
[*]  <td>  
[*]   <select ></select>  
[*]  </td>  
[*]  <td>  
[*]   <select ></select>  
[*]  </td>  
[*]  <td>  
[*]   <div >  
[*]    <select></select>  
[*]   </div>  
[*]  </td>  
[*] </tr>  
[*] <tr>  
[*]  <td><input type="button" value="dom" ></td>  
[*]  <td><input type="button" value="object" ></td>  
[*]  <td><input type="button" value="inner" ></td>  
[*] </tr>  
[*]</table>  
[*]</body>  
[*]  
[*]</html> 
页: [1]
查看完整版本: 动态给select添加选项的常用方法