日期:2014-05-16  浏览次数:20300 次

JS去掉<select>中重复的<option>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>My JSP 'MyJsp.jsp' starting page</title>
	<meta http-equiv="pragma" content="no-cache">
	<meta http-equiv="cache-control" content="no-cache">
	<meta http-equiv="expires" content="0">    
	<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
	<meta http-equiv="description" content="This is my page">
	<!--
	<link rel="stylesheet" type="text/css" href="styles.css">
	-->

  </head>
  <script type="text/javascript">
  function test()
  {
  	//(1)将所有option内容保存
	var temp = document.getElementsByTagName("option");
  	var array = new Array(temp.length);
	for (var i = 0, length= temp.length; i < length; i++){
		array[i] = temp[i].innerText;
    }
	
	//(2)将所有相同的option内容去掉
	var data={};	
	var desiredArr=new Array();  
	for(var i=0;i<array.length;i++){  
		data[array[i]]=array[i];  
	} 
	
	for(var pro in data){  
	  desiredArr.push(data[pro])  
	}  
	
	//(3)删掉所有子节点
	 var parent = document.getElementById("test2");  
     //这里因为childNodes节点会动态变下标,所以用0的index实现全部删除  
     for (var i = 0, length= parent.childNodes.length; i < length; i++){  
         parent.removeChild(parent.childNodes[0]);  
     } 
	 
	 //(4)添加过滤后的子节点
     for (var i = 0, length= desiredArr.length; i < length; i++){
		 var div_view=document.createElement("option");   
	  	 var text = document.getElementById("test2");  
	     div_view.innerText=desiredArr[i];  
	     text.appendChild(div_view); 
	 }
  }
  </script>
  <body>
	<fieldset>
	<legend>DSAFSD</legend> 
  <textarea rows="10" cols="10" id="test"></textarea>
    This is my JSP page. <br>
    </fieldset>
    <del>dadf</del>
    <select id="testSelect"  onfocus="test()" >
				<optgroup label="default" id="test2">
				<option>11</option>
				<option>11</option>
				<option>224</option>
				</optgroup>
    </select>
    
    <textarea rows="10" cols="100" id="testread">testtesttest111</textarea>
  </body>
</html>
?