省市級聯相容IE、Firefox、Google、360,Google360
注意:Google瀏覽器不允許載入本地的xml檔案,所以必須放到伺服器中,才能看到效果。
<!doctype html>
<html><head><meta charset="utf-8"><title>三級省市級聯</title><script>//IE中建立xml dom的方法function createXmlDomIE(){var arr=["MSXML2.DOMDocument.6.0","MSXML2.DOMDocument.5.0","MSXML2.DOMDocument.4.0","MSXML2.DOMDocument.3.0","MSXML2.DOMDocument","Microsoft.XMLDOM"];try{for(var i=0;i<arr.length;i++){//alert(arr[i]);return new ActiveXObject(arr[i]);}}catch(ex){throw ex;}}
//IE和firefox的xml dom實現有區別function xmlDom(){var xmldom;if(window.ActiveXObject){ //xml文檔對象xmldom=createXmlDomIE();}else if(document.implementation&&document.implementation.createDocument){//createDocument(); 第一個是命名空間 第二個參數跟標籤名 第三個參數doc類型xmldom=document.implementation.createDocument("","",null);}else{throw new Error("您的瀏覽器不支援XML DOM");}return xmldom;}window.onload=function(){var xmldom;if(window.DOMParser&&!window.ActiveXObject){ //如果是Google瀏覽器並且不是IE瀏覽器var xmlhttp=new XMLHttpRequest(); xmlhttp.open("GET","city.xml",false); xmlhttp.send(null); if(xmlhttp.readyState == 4){ xmldom = xmlhttp.responseXML.documentElement; } }else{xmldom=xmlDom();xmldom.async=false;xmldom.load("city.xml"); //載入xml檔案}var sheng=document.getElementById("sheng");var shi=document.getElementById("shi");var xian=document.getElementById("xian");//擷取所有的省份var shengs=xmldom.getElementsByTagName("province");//將所有的省添加到省的下拉式清單中for(var i=0;i<shengs.length;i++){addOption(shengs[i],sheng);}var cities;//在sheng的下拉式清單上判斷一個change事件sheng.onchange=function(){var flag=0;//擷取當前選擇的省的索引var index=sheng.options.selectedIndex;shi.length=0; //清空市xian.length=0; //清空縣cities=shengs[index].childNodes; //擷取選中的省下的所有市for(var j=0;j<cities.length;j++){if(cities[j].nodeType==1){//判斷當前節點是否為元素節點addOption(cities[j],shi); //將當前市添加的市的下拉式清單中if(flag==0){var areas=cities[j].childNodes; //擷取第一個市下的所有縣for(var k=0;k<areas.length;k++){addOption(areas[k],xian);}flag=1;}}}}//當市發生改變時shi.onchange=function(){xian.length=0; //清空縣//擷取選中的市的codevar mycode=shi.value;var shis=xmldom.getElementsByTagName("city"); //取出所有市for(var i=0;i<shis.length;i++){if(shis[i].nodeType==1){//如果是元素節點var youcode=shis[i].getAttribute("postcode"); //取出當前市的codeif(mycode==youcode){//如果當前是的code跟我選擇的市的code一樣var xians=shis[i].childNodes; //擷取當前市的所有縣for(var j=0;j<xians.length;j++){ //迴圈添加所有縣if(xians[j].nodeType==1){addOption(xians[j],xian);}}}}}}}function addOption(arrs,obj){if(arrs.nodeType==1){var opt=document.createElement("option");opt.appendChild(document.createTextNode(arrs.getAttribute("name")));opt.setAttribute("value",arrs.getAttribute("postcode"));obj.appendChild(opt);}}
</script></head>
<body><div> <select id="sheng" style="width:160px;border:1px solid #F93;"></select> <select id="shi" style="width:160px;border:1px solid #F93;"></select> <select id="xian" style="width:160px;border:1px solid #F93;"></select> </div></body></html>