js代码
//实现对xml文档的读取: function loadXMLDoc(dname) { try // Internet Explorer { xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); } catch (e) { try // Firefox, Mozilla, Opera, etc. { xmlDoc = document.implementation.createDocument("", "", null); } catch (e) { alert(e.message) } } try { xmlDoc.async = false; xmlDoc.load(dname);//加载xml文档 return (xmlDoc); } catch (e) { alert(e.message) } return (null); }
//实现对xml文档的操作: var stateSelectObj = document.getElementById("state"); var citySelectObj = document.getElementById("city"); var regionSelectObj = document.getElementById("region"); //初始化一个请选择:html dom stateSelectObj.add(new Option("--请选择--","")); citySelectObj.add(new Option("--请选择--","")); regionSelectObj.add(new Option("--请选择--","")); //从XML中读取所有的省份,给stateSelect赋值 var xmlDoc = loadXMLDoc("LocList.xml");//获取到代表XML文件的那个Document对象 var xmlStateNodes = xmlDoc.getElementsByTagName("State"); for(var i=0;i<xmlStateNodes.length;i++){ var xmlStateName = xmlStateNodes[i].getAttribute("Name"); var xmlStateCode = xmlStateNodes[i].getAttribute("Code"); stateSelectObj.add(new Option(xmlStateName,xmlStateCode)); } //给省份select注册onchange事件 stateSelectObj.onchange=function(){ //清空 citySelectObj.length=0; citySelectObj.add(new Option("--请选择--","")); if(this.value!=""){ for(var i=0;i<xmlStateNodes.length;i++){ //在xml中查找所有的State标签,看谁的Code属性和value值一样 var xmlStateCode = xmlStateNodes[i].getAttribute("Code"); if(this.value==xmlStateCode){ //调用该标签的getElementsByTagName,找到子标签。 var xmlCityNodes = xmlStateNodes[i].getElementsByTagName("City"); for(var j=0;j<xmlCityNodes.length;j++){ var xmlCityName = xmlCityNodes[j].getAttribute("Name"); var xmlCityCode = xmlCityNodes[j].getAttribute("Code"); //添加城市html citySelectObj.add(new Option(xmlCityName,xmlCityCode)); } break; } } } } //给市级城市添加onchange事件 citySelectObj.onchange=function() { //清空 regionSelectObj.length=0; regionSelectObj.add(new Option("--请选择--","")); if(this.value!="") { for(var i=0;i<xmlStateNodes.length;i++) { var xmlStateCode = xmlStateNodes[i].getAttribute("Code"); if(stateSelectObj.value==xmlStateCode) { var xmlCityNodes = xmlStateNodes[i].getElementsByTagName("City"); for(var j=0;j<xmlCityNodes.length;j++) { if(this.value==xmlCityNodes[j].getAttribute("Code")) { var xmlregionNodes = xmlCityNodes[j].getElementsByTagName("Region"); for(var k=0;k<xmlregionNodes.length;k++) { var xmlregionName = xmlregionNodes[k].getAttribute("Name"); var xmlregionCode = xmlregionNodes[k].getAttribute("Code"); //添加城市html regionSelectObj.add(new Option(xmlregionName,xmlregionCode)); } } } } } } }
html:
1 2 3 4 5 6 |
|
xml文档内容:
实现:
时间: 2024-09-05 06:31:43