首先看效果展示: http://kugaoheng.com/yanshi/08/0712.html
1.首先是HTML页面代码
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <select name="province" id="province"> <option value="11">请选择…</option> <option value="吉林省">吉林省</option> <option value="辽宁省">辽宁省</option> <option value="山东省">山东省</option> </select> <select name="city" id="city"> <option value="">请选择…</option> </select> <script> window.onload = function (){ // console.log( parseXML(province.xml)); document.getElementById("province").onchange = function(){ // console.log(this.value); var xmlDoc = parseXML("province1.xml"); var provinceXmlElement = xmlDoc.getElementsByTagName("province"); // alert(provinceXmlElement.length); var cityNode = document.getElementById(‘city‘); var options = cityNode.getElementsByTagName("option"); for (var m = options.length - 1; m > 0; m--) { cityNode.removeChild(options[m]); } if ( this.value == "11" ){ // console.log(123); return; } else { for (var i = 0; i < provinceXmlElement.length; i++){ // console.log(provinceXmlElement[i].getAttribute("name")); if ( provinceXmlElement[i].getAttribute("name") == this.value ){ // console.log(provinceXmlElement[i].getAttribute("name")); var allTextNodes = provinceXmlElement[i].getElementsByTagName("city"); console.log(allTextNodes.length); for (var k = 0; k < allTextNodes.length; k++) { var optionNode = document.createElement("option"); optionNode.innerHTML = allTextNodes[k].innerHTML; cityNode.appendChild(optionNode); } } } } var optionNodes = provinceXmlElement.childNodes; // console.log(provinceXmlElement[1].childNodes); }; }; function parseXML(fileXmlName){ var xmlDoc; if (window.XMLHttpRequest){// code for IE7+, Firefox, Chrome, Opera, Safari xmlhttp=new XMLHttpRequest(); } else {// code for IE6, IE5 xmlhttp=new ActiveXObject("Microsoft.XMLHTTP"); } xmlhttp.open("GET",fileXmlName,false); xmlhttp.send(); xmlDoc=xmlhttp.responseXML; // try { // xmlDoc = new ActiveXObject("Microsoft.XMLDOM"); // } catch (e) { // try { // xmlDoc = document.implementation.createDocument("","",null); // } catch (e){ // alert(e.message); // return; // } // } // xmlDoc.async = false; // xmlDoc.load(fileXmlName); return xmlDoc; } </script> </body> </html>
2.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> <city>铁岭</city> </province> <province name="山东省"> <city>济南</city> <city>青岛</city> <city>威海</city> <city>烟台</city> <city>潍坊</city> </province> </china>
3. 注意事项
(1) HTML解析xml文件需要在服务器环境下运行,在本地不起作用。
(2)JS中load方法不起作用,需要用open,send方法。
(3)xml文件保存时保存为utf-8编码方式,否则会出现乱码,导致代码无法正常运行。
可以试试这种方法, 点击跳转 .
我之前以为是编码问题,但是我的名字是province.xml这个文件名不好用,在文件名后面加个数字就好用了,如province1.xml,也不知道是什么原因造成的.结果是可行的,