<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html >
<head>
<meta http-equiv="content-type" content="text/html; charset=GBK">
<title>js 动态 增加 删除 select 子项option</title>
<script type="text/javascript">
function addOption(){
var obj=document.getElementByIdx("test");
var index=obj.options.length;
obj.options.add(new Option("子项"+index,index));
}
function delOption(){
var obj=document.getElementByIdx("test");
if(0<obj.options.length){
//obj.options.remove(obj.selectedIndex); //IE 可用
obj.options[obj.selectedIndex]=null;//IE FF 均可
for(var i=0;i<obj.options.length;i++){//for 只为重新排序...可以忽略
obj.options[i].text="子项"+i;
obj.options[i].value=i;
}
if(0<obj.options.length){//第一项选择状态
obj.options[0].selected=true;
}
}
}
function delAll(){
var obj=document.getElementByIdx("test");
obj.options.length=0;
}
function selectIndex(){
var obj=document.getElementByIdx("test");
if(0<obj.options.length){
var option=obj.options[obj.selectedIndex];
alert("当前选中项索引="+obj.selectedIndex+";text="+option.text+";value="+option.value);
}
}
</script>
</head>
<body >
<select id='test'style='width:100px;'>
</select>
<input type='button' value='添加' οnclick='addOption()'/>
<input type='button' value='删除当前选中项' οnclick='delOption()'/>
<input type='button' value='删除全部' οnclick='delAll()'/>
<input type='button' value='当前选中项信息' οnclick='selectIndex()'/>
</body>
</html>