所有代码都是在写在JS中。首先,解析XML 、然后把XML中的内容放进页面中的select选项里。
XML文件:
<?xml version="1.0" encoding="utf-8"?> <cities> <province name="北京"> <city>大兴</city> <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> </province> <province name="河南"> <city>郑州</city> <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> </province> </cities>
页面:
<body>
<h1>解析xml文件实现省市级联下拉菜单</h1>
<div>
<span>
<select id="province" name="province">
<option>请选择省</option>
</select>
</span>
<span>
<select id="cities" name="city">
<option>请选择相应省下面的市</option>
</select>
</span>
</div>
</body>
JS:
<script type="text/javascript"> window.onload = function(){ var xmlDom; try { //针对的是IE浏览器 创建一个空的微软 XML 文档对象 xmlDom = new ActiveXObject("Microsoft.XMLDOM"); } catch (err) { try { //在 Firefox 及其他浏览器中的 XML 解析器 //创建一个空的 XML 文档对象。 xmlDom = document.implementation.createDocument("", "", null); } catch (e) { } } //关闭异步加载,这样确保在文档完全加载之前解析器不会继续脚本的执行 xmlDom.async = "false"; //解析器加载名为 "xxx.xml" 的 XML 文档、 xmlDom.load("city.xml"); //获取xml文件的根节点 var root = xmlDom.documentElement; //获取根节点下面的省节点 var provinces = root.childNodes; var province = document.getElementById("province"); for (var i = 0; i < provinces.length; i++) { //获取省节点的name属性的值 var name = provinces[i].getAttribute("name"); //创建一个option var opt = document.createElement("option"); //为option添加文本 opt.appendChild(document.createTextNode(name)); //添加到父节点中 province.appendChild(opt); } var cities = document.getElementById("cities"); province.onchange = function(){ var pce = document.getElementById("province"); var opts = pce.options; //根据下标获取选中的OPTION var opt1 = opts[pce.selectedIndex]; var name = opt1.innerHTML; for (var i = 0; i < provinces.length; i++) { //获取省节点的name属性的值 var name1 = provinces[i].getAttribute("name"); if (name == name1) { cities.length = 1;//每次改变的时候清空 var pros = provinces[i]; var citys = pros.childNodes; for (var j = 0; j < citys.length; j++) { //创建一个option var opt = document.createElement("option"); //为option添加文本 opt.appendChild(document.createTextNode(citys[j].text)); //添加到父节点中 cities.appendChild(opt); } } } } } </script>
效果图: