js 动态 增加 删除 select 子项 option

来源:互联网 发布:node.js php 对比 编辑:程序博客网 时间:2024/05/21 14:03
<!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.getElementById("test");
   var index=obj.options.length;
       obj.options.add(new Option("子项"+index,index));
 }
 function delOption(){
    var obj=document.getElementById("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.getElementById("test");
       obj.options.length=0;
 }
 function selectIndex(){
   var obj=document.getElementById("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='添加' onclick='addOption()'/>
<input type='button' value='删除当前选中项' onclick='delOption()'/>
<input type='button' value='删除全部' onclick='delAll()'/>
<input type='button' value='当前选中项信息' onclick='selectIndex()'/>
</body>
</html>
原创粉丝点击