js實現的國家、省、市級聯效果程式碼例項

admin發表於2017-03-24

本章節通過例項程式碼介紹一下如何實現國家、省市級聯效果,可能帶有國家的在實際應用中比較少,但是可以通過改造實現其他的級聯效果,程式碼如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
<meta charset=" utf-8">
<meta name="author" content="http://www.softwhy.com/" />
<title>螞蟻部落</title>
<script type="text/javascript"> 
var list=[{"name":"中國", 
"value":"86", 
"province":[{"name":"湖北", 
"value":"430000", 
"city":[{"name":"武漢","value":"wh"}, 
{"name":"黃岡","value":"hg"}, 
{"name":"襄陽","value":"xy"}]}, 
{"name":"河北", 
"value":"100000", 
"city":[{"name":"邯鄲","value":"hd"}, 
{"name":"保定","value":"bd"}, 
{"name":"石家莊","value":"sjz"}]}, 
 
{"name":"湖南", 
"value":"440000", 
"city":[{"name":"長沙","value":"cs"}, 
{"name":"株洲","value":"zz"}, 
{"name":"衡陽","value":"hy"}]}]}, 
{"name":"美國", 
"value":"22", 
"province":[{"name":"阿肯色", 
"value":"990000", 
"city":[{"name":"紐約","value":"ny"}, 
{"name":"華盛頓","value":"hsd"}, 
{"name":"波士頓","value":"bsd"}]}, 
 
{"name":"阿哈哈", 
"value":"980000", 
"city":[{"name":"AA","value":"ahd"}, 
{"name":"BB","value":"abd"}, 
{"name":"CC","value":"asjz"}]}] 
}]; 
 
function init(){ 
  var _country=document.getElementById("country"); 
  for(var e in list){ 
    var opt_1=new Option(list[e].name,list[e].value); 
    _country.add(opt_1); 
  } 
} 
 
function toProvince(){ 
  var _country=document.getElementById("country"); 
  var _province=document.getElementById("province"); 
  var _city=document.getElementById("city"); 
  var v_country=_country.value; 
 
  _province.options.length=1; 
  _city.options.length=1; 
 
  for(var e in list){ 
    if(list[e].value==v_country){ 
      for( var p in list[e].province){ 
        var opt_2=new Option(list[e].province[p].name,list[e].province[p].value); 
        _province.add(opt_2); 
     } 
     break; 
   } 
  } 
} 
 
 
function toCity(){ 
  var _country=document.getElementById("country"); 
  var _province=document.getElementById("province"); 
  var _city=document.getElementById("city"); 
 
  var v_country=_country.value; 
  var v_province=_province.value; 
 
  _city.options.length=1; 
 
 
  for(var e in list){ 
    if(list[e].value==v_country){ 
      for( var p in list[e].province){ 
        if(list[e].province[p].value==v_province){ 
          for(var cc in list[e].province[p].city){ 
            var opt_3=new Option(list[e].province[p].city[cc].name,list[e].province[p].city[cc].value); 
            _city.add(opt_3); 
          } 
          return; 
        } 
      } 
      break; 
    } 
  } 
} 
 
//--> 
</script> 
</head> 
<body onload="init();";> 
<select id="country" onchange="toProvince();"> 
<option value="-1">--請選擇國家---</option> 
</select> 
<select id="province" onchange="toCity();"> 
<option value="-1">--請選擇省份---</option> 
</select> 
<select id="city"> 
<option value="-1">--請選擇市區---</option> 
</select> 
</body> 
</html>

相關文章