JavaScript省市二级联动

cities.xml 

<?xml version="1.0" encoding="GB2312"?>
<china>
	<province name="吉林省">
		<city>长春</city>
		<city>吉林市</city>
		<city>四平</city>
		<city>松原</city>
		<city>通化</city>
	</province>
	<province name="辽宁省">
		<city>沈阳</city>
		<city>大连</city>
		<city>鞍山</city>
		<city>抚顺</city>
	</province>
	<province name="山东省">
		<city>济南</city>
		<city>青岛</city>
		<city>威海</city>
		<city>烟台</city>
		<city>潍坊</city>
	</province>
	<province name="湖北省">
		<city>武汉</city>
		<city>广水</city>
		<city>孝感</city>
		<city>荆州</city>
		<city>黄石</city>
		<city>鄂州</city>
		<city>黄冈</city>
	</province>
</china>	


city.html

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <title>二级联动</title>
    <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  </head>
  
  <body>
    <select id="province" >
    	<option>--请选择--</option>
    	<option value="湖北省">湖北省</option>
    	<option value="吉林省">吉林省</option>
    	<option value="辽宁省">辽宁省</option>
    	<option value="山东省">山东省</option>
    </select>
	
	<select id="city">
		<option>--请选择--</option>
	</select>
  </body>
  <script type="text/javascript">
  	document.getElementById("province").onchange=function(){
		//当前选中的省
		var provinceValue=this.value;	
		var cityNode=document.getElementById("city");
		
		//删除市下拉列表中的前一个省的城市项
		var cityOptions=cityNode.getElementsByTagName("option");
		for(var i=cityOptions.length-1;i>0;i--){
			cityNode.removeChild(cityOptions[i]);
		}
		
		
		var xmlDoc=parseXML("cities.xml");
		var xmlProvinceElements=xmlDoc.getElementsByTagName("province");
		
		//下拉列表中添加选中省的城市项	
		for(var i=0;i<xmlProvinceElements.length;i++){
			if(xmlProvinceElements[i].getAttribute("name")==provinceValue){
				var xmlCityElements=xmlProvinceElements[i].getElementsByTagName("city");
				for(var j=0;j<xmlCityElements.length;j++){
					var xmlCityName=xmlCityElements[j].firstChild.nodeValue;	
					var cityOptionElement=document.createElement("option");
					cityOptionElement.setAttribute("value",xmlCityName);
					cityOptionElement.appendChild(document.createTextNode(xmlCityName));
					cityNode.appendChild(cityOptionElement);
				}
				break;
			}
		}
		
	}
	
	
	/*
	 * 加载XML文件
	 * @param {Object} filename
	 */
	function parseXML(filename){
		try{		//Internet Explorer  创建一个空的xml文档
			xmlDoc=new ActiveXObject("Microsoft.XMLDOM");
		}catch(e){	// Firefox,Mozilla,Opera....
			try {
				xmlDoc=document.implementation.createsDocument("","",null);
			}catch(e){}
		}
		//关闭异步加载
		xmlDoc.async=false;
		//加载XML文档
		xmlDoc.load(filename);
		return xmlDoc;
	}
  </script>
</html>


JavaScript省市二级联动,古老的榕树,5-wow.com

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。