DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript省市級聯功能實現方法實例詳解
javascript省市級聯功能實現方法實例詳解
編輯:關於JavaScript     

本文實例講述了javascript省市級聯功能實現方法。分享給大家供大家參考,具體如下:

初步實現方法:

<html>
<head>
<script language="javascript">
 function changecity(){
 var province = document.form1.selprovince.value;
 var newoption1,newoption2;
 switch(province){
  case "四川省":
  newoption1 = new Option("成都市", "chengdu");
  newoption2 = new Option("綿陽市", "mianyang");
  break;
   case "湖北省" : 
  newoption1= new Option("武漢市","wuhan");
  newoption2= new Option("襄樊市","xiangfan");
  break;
   case "山東省" : 
   newoption1= new Option("青島市","qingdao");
   newoption2= new Option("煙台市","yantai");
  break;  
 }
 document.form1.selcity.options.length=0;
 document.form1.selcity.options.add(newoption1);
 document.form1.selcity.options.add(newoption2);
 }
</script>
</head>
<form name="form1" action="" method="post">
 <select name="selprovince" onchange="changecity()">
 <option>--請選擇開戶帳號的省份--</option>
 <OPTION value="四川省">四川省</OPTION>
 <OPTION value="山東省">山東省</OPTION>
 <OPTION value="湖北省">湖北省</OPTION>
 </select>
 <select name="selcity">
 <option>--請選擇開戶帳號的城市--</option>
 </select>
</form>
</html>

改進實現方法:

<html>
<head>
<script language="javascript">
 function changecity(){
 var cityList = new Array();
 cityList[0]=['成都', '綿陽', '德陽', '自貢'];
 cityList[1]=['濟南', '青島', '淄博', '棗莊'];
 cityList[2]=['武漢', '宜昌', '荊州', '襄樊'];
 var pindex = document.form1.selprovince.selectedIndex-1;
 var newoption1;
 document.form1.selcity.options.length = 0;
 for(var j in cityList[pindex]){
  newoption1 = new Option(cityList[pindex][j], cityList[pindex][j]);
  document.form1.selcity.options.add(newoption1);
 }
 }
</script>
</head>
<form name="form1" action="" method="post">
 <select name="selprovince" onchange="changecity()">
 <option>--請選擇省份--</option>
 <OPTION value="四川省">四川省</OPTION>
 <OPTION value="山東省">山東省</OPTION>
 <OPTION value="湖北省">湖北省</OPTION>
 </select>
 <select name="selcity">
 <option>--請選擇城市--</option>
 </select>
</form>
</html>

改進方法2:

<html>
<head>
<script language="javascript">
 function citychange(){
 var cityList = new Array();
 cityList['遼寧省'] = ['沈陽','鞍山','大連'];
 cityList['山東省'] = ['濟南','煙台','蓬萊'];
 cityList['山西省'] = ['太原','大同','平遙'];
 var pindex = document.form1.selprovince.value;
 var newoption1;
 document.form1.selcity.options.length = 0;
 for(var i in cityList[pindex]){
  newoption1 = new Option(cityList[pindex][i],cityList[pindex][i]);
  document.form1.selcity.options.add(newoption1);
 }
 }
</script>
</head>
<form action="" name="form1" method="post">
 <select name="selprovince" onchange="citychange()">
 <option>請選擇省份</option>
 <OPTION value="遼寧省">遼寧省</OPTION>
 <OPTION value="山東省">山東省</OPTION>
 <OPTION value="山西省">山西省</OPTION>
 </select>
 <select name="selcity">
 <option>請選擇城市</option>
 </select>
</form>
</html>

希望本文所述對大家JavaScript程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved