<script type="text/javascript">
window.onload = function() {
/**
* 加载xml
*/
function parseXML() {
var xmlhttp;
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","xml/city.xml",false);
xmlhttp.send();
xmlDoc = xmlhttp.responseXML;
return xmlDoc;
};
/**
*获得select的文本值
*这里采用这种做法的好处是为了兼容ie和ff
*/
function getName(obj)
{
var index = obj.selectedIndex; // 选中索引
var text = obj.options[index].text;
return text;
}
/*
*如果城市里面已经有数据,就清空
*
*/
function initCity(cityLen,citys,citysSubElements)
{
if(cityLen>1)
{
for (var int2 = 1,l=cityLen; int2 < l; int2++)
{
var array_element = citysSubElements[1];
citys.removeChild(array_element);
}
}
}
/**
*添加城市
*/
function addCity(arrayElement,citys)
{
for ( var int2 = 0,k = arrayElement.length; int2 < k; int2++)
{
var array_element = arrayElement[int2];
//构造节点
var cityOption = document.createElement("option");
var txtNode = document
.createTextNode(array_element.firstChild.nodeValue);
cityOption.appendChild(txtNode);
//添加相应的节点
citys.appendChild(cityOption);
}
}
document.getElementById("provice").onchange = function()
{
//解析相应的xml
var doc = parseXML();
//获得城市列表
var provices = doc.getElementsByTagName("provice");
//获得要显示的城市组件
var citys = document.getElementById("city");
var citysSubElements = citys.children;
var cityLen = citysSubElements.length;
// 初始化城市列表
initCity(cityLen,citysSubElements)
for ( var int = 0,j = provices.length; int < j; int++) //遍历省份列表
{
var array_element = provices[int];
if (array_element.getAttributeNode("name").nodeValue == getName(this)) //查找到所需的省份
{
//此处写法是为了兼容ie
var arrayElement = array_element.children||array_element.childNodes;//查找到所需的城市()
addCity(arrayElement,citys);
break;
}
}
}
}
</script>
<select id="provice">
<option>
请选择
</option>
<option>
辽宁
</option>
<option>
河南
</option>
<option>
广东
</option>
</select>
<select id="city">
<option>
请选择
</option>
</select>
<?xml version="1.0" encoding="GBK"?>
<china>
<provice name="辽宁">
<city>沈阳市</city>
<city>铁岭县</city>
<city>盘锦市</city>
<city>锦州市</city>
</provice>
<provice name="河南">
<city>郑州</city>
<city>南阳</city>
<city>焦作</city>
<city>新乡</city>
</provice>
<provice name="广东">
<city>深圳</city>
<city>珠海</city>
<city>东莞</city>
<city>梅州</city>
</provice>
</china>
原文链接:https://www.f2er.com/xml/299849.html