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
有用 | 无用
猜你喜欢
您可能感兴趣的文章:
- 判定对象是否为window的js代码
- javascript 定义新对象方法
- javascript inneHTML的地雷
- javascript 包裹节点 提高效率
- Jquery乱码的一次解决过程 图解教程
- JavaScript CSS修改学习第六章 拖拽
- JavaScript CSS修改学习第五章 给“上传”添加样式
- JavaScript CSS 修改学习第四章 透明度设置
- JavaScript CSS修改学习第三章 修改样式表
- JavaScript CSS修改学习第二章 样式
- JavaScript CSS修改学习第一章 查找位置
- JavaScript DOM 学习第九章 选取范围的介绍
- JavaScript DOM学习第八章 表单错误提示
- JavaScript DOM 学习第七章 表单的扩展
- JavaScript DOM 学习第五章 表单简介
- JavaScript DOM学习第四章 getElementByTagNames
- JavaScript DOM 学习第三章 内容表格
- JavaScript DOM 学习第二章 编辑文本
- javascript中的链式调用