1 <html> 2 3 <head> 4 5 <title></title> 6 <script> 7 function $(obj){ 8 return document.getElementById(obj); 9 } 10 //返回xmldoc,处理了浏览器差异不同的影响 11 function getXmlDoc(){ 12 var xmldoc=null; 13 try{ 14 xmldoc=new ActiveXObject('Microsoft.XMLDOM');//微软的 XML 解析器内建于IE5以及更高的版本中 15 16 }catch(e){ 17 xmldoc = document.implementation.createDocument("","",null);//其它浏览器 Firefox, Mozilla, Opera, etc. 18 } 19 return xmldoc; 20 } 21 22 //定义变量 23 var xmldoc; 24 var province = null; 25 var city = null; 26 var country =null; 27 var list=null; //数组,用来保存从XML中得出的所有省市区数据 28 //定义一个方法,用于初始化数据,从 2.xml加载数据 29 function init(){ 30 xmldoc=getXmlDoc(); 31 xmldoc.async=false; 32 xmldoc.load('2.xml'); 33 province =$('province'); 34 city = $('city'); 35 country = $('country'); 36 list=new Array(); 37 } 38 39 window.onload=function(){ 40 init(); 41 province.options.length=0; 42 var provinces = xmldoc.getElementsByTagName("province"); //得到根节点 43 44 45 //从XML中得出省市区存至list中如:list['湖南省']=new Array('长沙市,衡阳市') list['长沙市']=new Array('长沙县,渡河区'); 46 47 for(var i=0;i<provinces.length;i++){ 48 if(provinces[i].nodeType==1){ 49 //往省份下拉列表中加数据 50 province.options.add(new Option(provinces[i].getAttribute("pname"),provinces[i].getAttribute("pname"))); 51 list[provinces[i].getAttribute("pname")]=new Array(); //将list[省份名]定义为数组 52 for(var j=0;j<provinces[i].childNodes.length;j++){ 53 if(provinces[i].childNodes[j].nodeType==1){ 54 list[provinces[i].getAttribute("pname")].push(provinces[i].childNodes[j].getAttribute("cname")); 55 list[provinces[i].childNodes[j].getAttribute("cname")] = new Array(); //将list[城市名]定义为数组 56 for(var a=0;a<provinces[i].childNodes[j].childNodes.length;a++){ 57 list[provinces[i].childNodes[j].getAttribute("cname")].push(provinces[i].childNodes[j].childNodes[a].getAttribute("cname")); 58 } 59 } 60 } 61 } 62 } 63 64 showcity(); 65 66 //为省,城市,两个下拉列表onchang事件分别绑定函数。 67 city.onchange=showcountry; 68 province.onchange=showcity; 69 } 70 71 function showcity(){ 72 73 city.options.length=0; 74 for(var i in list[province.value]){ 75 city.options.add(new Option(list[province.value][i],list[province.value][i])); 76 } 77 } 78 79 80 function showcountry(){ 81 country.options.length=0; 82 for(var i in list[city.value]){ 83 country.options.add(new Option(list[city.value][i],list[city.value][i])); 84 } 85 } 86 87 </script> 88 </head> 89 <body> 90 省:<select id="province" name="province"></select> 91 市:<select id="city" name="city"></select> 92 区:<select id="country" name="country"></select> 93 </body> 94 </html> 1 <?xml version="1.0" encoding="UTF-8"?> 2 <test> 3 4 <province pname="湖南省"> 5 <city cname="长沙市"> 6 <country cname="长沙县"></country> 7 <country cname="渡河区"></country> 8 </city> 9 <city cname="衡阳市"> 10 <country cname="珠晖区"></country> 11 <country cname="石鼓区"></country> 12