1. 程式人生 > >JS下拉框之間的聯動(兩級)

JS下拉框之間的聯動(兩級)

<html>  

 <meta charset="utf-8">
<body>  
  
<select id="first" onChange="change()">  
   <option selected="selected">湖北</option>  
   <option>廣東</option>  
</select>  
  
<select id="second">  
   <option>黃岡</option>  
   <option selected="selected">武漢</option>  
</select>  
  
  
<script>  
function change()  
{  
   var x = document.getElementById("first");  
   var y = document.getElementById("second");  
   y.options.length = 0; // 清除second下拉框的所有內容  
   if(x.selectedIndex == 0)  
   {  
        y.options.add(new Option("黃岡", "0"));  
        y.options.add(new Option("武漢", "1", false, true));  // 預設選中省會城市  
   }  
  
   if(x.selectedIndex == 1)  
   {  
        y.options.add(new Option("深圳", "0"));  
        y.options.add(new Option("廣州", "1", false, true));  // 預設選中省會城市  
        y.options.add(new Option("肇慶", "2"));  
   }  
  
}  
</script>  
    
</body>  
</html>