javascript(JS)完全控制Select下拉框

< select  id ="mysel"  name ="mysel" >
  
< option  value ="1" > 1 xxxxxxxxxx </ option >
  
< option  value ="2" > 2 yyyyyyyyyy </ option >
  
< option  value ="3" > 3 zzzzzzzzzz </ option >
  
< option  value ="4" > 4 wwwwwwwwww </ option >
</ select >
< button  onclick ="setSel(3)" > 设置第3项为选中项 </ button >
< button  onclick ="clearSel()" > 清空选择框 </ button >
< button  onclick ="fillSel()" > 填充选择框 </ button >
< button  onclick ="removeSel()" > 移除第一项 </ button >
< button  onclick ="editSel()" > 修改第一项 </ button >

< script  type ="text/javascript" >
    
function  setSel(str){
        
with (document.all){    
            
for ( var  i = 0 ;i < mysel.options.length;i ++ ){                
                
if  (mysel.options[i].value == str){
                    mysel.selectedIndex
= i;
                    
break ;
                }
            }            
        }
    }


    
function  clearSel(){
        
with (document.all){    
            mysel.options.length
= 0 ;
        }
    }

    
function  fillSel(){
        
with (document.all){
            mysel.options.length
= 0 ;
            mysel.options[
0 =   new  Option( " 1 xxxxxxxxxx " , " 1 " );
            mysel.options[
1 =   new  Option( " 2 yyyyyyyyyy " , " 2 " );
            mysel.options[
2 =   new  Option( " 3 zzzzzzzzzz " , " 3 " );
            mysel.options[
3 =   new  Option( " 4 wwwwwwwwww " , " 4 " );
            mysel.options[
4 =   new  Option( " 5 aaaaaaaaaa " , " 5 " );

            mysel.selectedIndex 
=   4 ;
        }
    }

    
function  removeSel(){
        
with (document.all){
            mysel.remove(
0 );
            
if  (mysel.options.length > 0 ){
                mysel.selectedIndex
= 0 ;
            }
        }
    }

    
function  editSel(){
        
with (document.all){
            
if  (mysel.options.length > 0 ){
                mysel.options[
0 =   new  Option( " 这是新的第一项 " , " new Value " )
                mysel.selectedIndex
= 0 ;
            }
        }
    }
</ script >

你可能感兴趣的:(JavaScript)