有两个文件,分别是city.html文件city.xml文件,city.html如下:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>无标题文档</title> </head> <body> <select name="province" id="province"> <option value="">请选项....</option> <option value="安徽">安徽</option> <option value="江苏">江苏</option> </select> <select name="city" id="city"> <option value="">请选项....</option> </select> </body> <script language="javascript"> window.onload = function() { //右移 document.getElementById("province").onchange = function() { document.getElementById("city").innerHTML="<option value=''>请选项....</option>"; var xmlDoc; xmlDoc = getXmlDoc("city.xml"); var chinaElements = xmlDoc.getElementsByTagName("china"); var provinceElements = xmlDoc.getElementsByTagName("province"); var cityElements = document.getElementById("city") for ( var i = 0; i < provinceElements.length; i++) { var provinceName = provinceElements[i].getAttribute("name"); if (provinceName == this.value) { var cityName = provinceElements[i].childNodes[0].childNodes[0]; for ( var j1 = 0; j1 < provinceElements[i].childNodes.length; j1++) { for ( var j2 = 0; j2 < provinceElements[i].childNodes[j1].childNodes.length; j2++) { var cityName = provinceElements[i].childNodes[j1].childNodes[j2]; var optionElement = document .createElement("option"); optionElement.setAttribute("value", cityName.nodeValue); var optionTextNode = document .createTextNode(cityName.nodeValue); optionElement.appendChild(optionTextNode); cityElements.appendChild(optionElement); } } } } } function getXmlDoc(fileXmlpath) { 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", fileXmlpath, false); xmlhttp.send(); xmlDoc = xmlhttp.responseXML; return xmlDoc; } } </script> </html> city.xml文件
<?xml version="1.0" encoding="utf-8"?> <china><province name="安徽"><city name="aa">安庆</city><city>合肥</city><city>阜阳</city><city>马鞍山</city></province><province name="江苏"><city>南京</city><city>无锡</city><city>苏州</city><city>南通</city></province></china>