写一个js对xml的解析,做一个select的2级联动,很用的,以后只要改xml文件就行了
@H_403_3@<!DOCTYPE @H_403_3@html PUBLIC @H_403_3@ "-//W3C//DTDHTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"@H_403_3@>
@H_403_3@<Meta http-equiv="Content-Type"content="text/html; charset=UTF-8"@H_403_3@>
@H_403_3@<title@H_403_3@>Insert title here@H_403_3@</title@H_403_3@>
@H_403_3@<script type="text/javascript"@H_403_3@>
window.onload = function() {
var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");//创建微软的解析器
var provinceElement = document.getElementById("province");
var cityElement = document.getElementById("city");//获取省和城市的下俩列表元素节点
xmlDoc.async = "false";//设置异步关闭
xmlDoc.load("fish.xml");//加载xml
var txt = xmlDoc.getElementsByTagName("province");//获取xml标签名字
for ( var i = 0; i < txt.length; i++) {//可以获取xml里面属性
var name = txt[i].getAttribute("name");
var p = document.createElement("option");//创建option元素节点
p.appendChild(document.createTextNode(name));//创建文本节点
province.appendChild(p);//挂载节点到第一个下拉表中
}
provinceElement.onchange = function() {
var selectprovinceElement =provinceElement[provinceElement.selectedIndex];
//alert(selectprovinceElement.value);
var selectValue = selectprovinceElement.value;//获取选中元素的值
cityElement.length=1;//这句话很重要。为了下次点击的时候,将上次的select里面的option清除
for ( var i = 0; i < txt.length; i++) {
var name = txt[i].getAttribute("name");//再一次或得xml的省份
if (name == selectValue) {//如果相等就读取省下的子节点
var city = txt[i].childNodes;//获取该节点的孩子节点
for ( var j = 0; j < city.length; j++) {
var optionElement = document.createElement("option");
//city[j].childNodes[0].nodeValue;//获取xml省下的所有子节点
var optionTextElement = document
.createTextNode(city[j].childNodes[0].nodeValue);//创建一个文本节点
optionElement.appendChild(optionTextElement);
cityElement.appendChild(optionElement);//跟第一次样
}
}
}
}
}
@H_403_3@<select id="province"@H_403_3@>
@H_403_3@<option@H_403_3@>--请选择省--@H_403_3@</option@H_403_3@>
@H_403_3@<select id="city"@H_403_3@>
@H_403_3@<option@H_403_3@>--请选择市--@H_403_3@</option@H_403_3@>
@H_403_3@
@H_403_3@
@H_403_3@
@H_403_3@Xml@H_403_3@文件@H_403_3@ fish.Xml
<?xmlversion="1.0" encoding="UTF-8"?>
<cities>
<province name=@H_403_519@"@H_403_519@浙江省@H_403_519@">
<city>杭州</city>
<city>嘉兴</city>
<city>温州</city>
<city>台州</city>
<city>丽水</city>
<city>金华</city>
</province>
<province name=@H_403_519@"@H_403_519@吉林省@H_403_519@">
<city>长春</city>
<city>白山</city>
<city>吉林</city>
<city>榆树</city>
<city>四平</city>
</province>
</cities>
原文链接:https://www.f2er.com/ajax/166232.html