js实现“级联菜单”
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" /> 5 <title>级联效果</title> 6 <script language="javascript" type="text/javascript"> 7 window.onload = function(){ 8 document.getElementById("province").onchange = function(){ 9 var changeProvinceValue = this.value;//获取省变化的值 10 var cityElement = document.getElementById("city");//清空下拉选项的值 11 var cityoptionElements = cityElement.getElementsByTagName("option"); 12 for(var i=cityoptionElements.length -1 ;i >0;i--){ 13 cityElement.removeChild(cityoptionElements[i]); 14 } 15 //测试xml是否加载成功 16 var xmldoc = parseXml("city.xml"); 17 var provinceElement= null; 18 //定位到具体省 19 var xmlProvinceElements = xmldoc.getElementsByTagName("province"); 20 for(var i=0;i<xmlProvinceElements.length;i++){ 21 var xmlProvinceElement=xmlProvinceElements[i]; 22 var nameAttribute =xmlProvinceElement.getAttribute("name"); 23 if(changeProvinceValue == nameAttribute){ 24 provinceElement = xmlProvinceElement; 25 break; 26 } 27 } 28 if(provinceElement != null){ 29 var xmlCityElements=provinceElement.getElementsByTagName("city"); 30 for(var i=0 ; i<xmlCityElements.length;i++){ 31 var cityValue=xmlCityElements[i].firstChild.nodeValue; 32 var optionElement=document.createElement("option"); 33 optionElement.setAttribute("value",cityValue); 34 var cityTextElement=document.createTextNode(cityValue); 35 optionElement.appendChild(cityTextElement); 36 37 var cityElement=document.getElementById("city"); 38 cityElement.appendChild(optionElement); 39 } 40 } 41 } 42 } 43 function parseXml(filename){ 44 try{ 45 xmldoc =new ActiveXObject("Microsoft.XMLDOM"); 46 } 47 catch(e){ 48 try{ 49 xmldoc= document.implementation.createDocument("","",null); 50 } 51 catch(e){} 52 } 53 xmldoc.async = false; 54 xmldoc.load(filename); 55 return xmldoc; 56 } 57 </script> 58 </head> 59 60 <body> 61 <select id="province" name="province"> 62 <option value="">请选择</option> 63 <option value="吉林省">吉林省</option> 64 <option value="山东省">山东省</option> 65 <option value="辽宁省">辽宁省</option> 66 </select> 67 <select id="city" name="city"> 68 <option value="">请选择</option> 69 </select> 70 </body> 71 72 </html>
以下是xml文件(city.xml):
1 <?xml version="1.0" encoding="GB2312"?> 2 <china> 3 <province name="吉林省"> 4 <city>长春</city> 5 <city>松原</city> 6 <city>通化</city> 7 <city>四平</city> 8 </province> 9 <province name="辽宁省"> 10 <city>沈阳</city> 11 <city>大连</city> 12 <city>鞍山</city> 13 <city>抚顺</city> 14 </province> 15 <province name="山东省"> 16 <city>威海</city> 17 <city>济南</city> 18 <city>青岛</city> 19 <city>烟台</city> 20 </province> 21 </china>
效果:
下拉选择山东,右边的下拉出现相对应的城市。