js删除select中重复项的实现代码

  作者:bea

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="tex


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>删除select中重复项</title>
<style type="text/css">
body{ text-align:center;}
div{ width:400px; background:#f1f5fa; margin:auto; border:solid 1px #BFC9DB; padding:10px;}
h4{ }
a{text-align:right; display:block; font-size:12px;}
</style>
<script type="text/javascript">
/*定义全局函数$*/
function $(id){
return document.getElementById(id);
}
/*初始化select*/
function InitialSelectOption(id){
var oSel=$(id);
var aOptions=["Wang Hongjian","Wang Hongjian","Nichoal Smith","Nichoal Smith","David Gates","David Gates","David Gates","Wang Hongjian","Wang Hongjian","Nichoal Smith","Nichoal Smith","David Gates","David Gates","David Gates"];
var i=0;
oSel.options.length=0;
while(i<aOptions.length){
var option=new Option(aOptions[i],i);
oSel.options.add(option);
i++;
}
oSel.setAttribute("size",i-1);
$("btnDistinct").removeAttribute("disabled");
}
/*删除重复项*/
function DistinctSelectOption(id){
var oSel=$(id);
var i=0;
while(i<oSel.options.length){
var j=i+1;
while(j<oSel.options.length){
if(oSel.options[i].text==oSel.options[j].text){
oSel.options[j]=null;//不可使用oSel.options.remove(j),因为不兼容firefox
}else{
j++;
}
}
i++;
}
oSel.setAttribute("size",i);
$("btnDistinct").setAttribute("disabled","disabled");
}
window.onload=function(){
/*初始化*/
$("btnInital").onclick=function(){InitialSelectOption("sel");};
/*删除重复项*/
$("btnDistinct").onclick=function(){DistinctSelectOption("sel");};
$("btnDistinct").setAttribute("disabled","disabled");
}
</script>
</head>

<body>
<div>
<h4>删除select重复项演示</h4>
<a href="http:///" target="_blank" title="http:///">http:///</a>
<hr />
<select id="sel" multiple="multiple" size="1"><option>待初始化…</select>
<hr />
<button id="btnInital">初始化</button>
<button id="btnDistinct">删除重复项</button>
</div>
</body>
</html>




[Ctrl+A 全选 注:
如需引入外部Js需刷新才能执行]


效果

来源:51obj


有用  |  无用

猜你喜欢