js+xml生成级联下拉框代码

需要默认选中时,定义一个变量 var cityId=城市id
下面是js代码

复制代码 代码如下:


function readxml() {
var XmlDoc = null;
if (window.ActiveXObject) {
XmlDoc = new ActiveXObject("Microsoft.XMLDOM");
XmlDoc.async = false;
XmlDoc.load(path + "/web/common/regions.xml");
browse = "ie";
} else if (document.implementation
&& document.implementation.createDocument) {
xmlDoc = document.implementation.createDocument('', '', null);
xmlDoc.load("regions.xml");
browse = "ff";
} else {
alert('未做与该浏览器的兼容!');
}
var root = XmlDoc.documentElement;
// 获取根节点下面的省节点
var provinces = root.childNodes;
var province = document.getElementByIdx_x_x("province");
var cities = document.getElementByIdx_x_x("regId");
for ( var i = 0; i < provinces.length; i++) {
// 获取省节点的name属性的值
var name = provinces[i].getAttribute("name");
// 创建一个option
var opt = document_createElement_x_x("option");
// 为option添加文本
opt.a(document_createTextNode(name));
// 添加到父节点中
if(cityId!=null&&cityId!=""){
var citys=provinces[i].childNodes;
for(var j=0;j<citys.length;j++){
if(citys[j].getAttribute("id")==cityId){
opt.selected="selected";
for ( var j = 0; j < citys.length; j++) {
// 创建一个option
var opt1 = document_createElement_x_x("option");
opt1.value = citys[j].getAttribute("id");
// 为option添加文本
opt1.a(document_createTextNode(citys[j]
.getAttribute("name")));
// 添加到父节点中
if(citys[j].getAttribute("id")==cityId){
opt1.selected="selected";
}
cities.a(opt1);
}
}
}
}
province.a(opt);
}
province.onchange = function() {
var pce = document.getElementByIdx_x_x("province");
var opts = pce.options;
var opt1 = opts[pce.selectedIndex];
var name = opt1.innerText;
for ( var i = 0; i < provinces.length; i++) {
// 获取省节点的name属性的值
var name1 = provinces[i].getAttribute("name");
if (name == name1) {
cities.length = 1;// 每次改变的时候清空
var pros = provinces[i];
var citys = pros.childNodes;
for ( var j = 0; j < citys.length; j++) {
// 创建一个option
var opt1 = document_createElement_x_x("option");
opt1.value = citys[j].getAttribute("id");
// 为option添加文本
opt1.a(document_createTextNode(citys[j]
.getAttribute("name")));
// 添加到父节点中
cities.a(opt1);
}
}
}
}
}


下面是xml结构

复制代码 代码如下:


<?xml version="1.0" encoding="utf-8"?>
<regions>
<province>
<city isOpen="1" />
<city isOpen="1" />
<city isOpen="1" />
<city isOpen="0" />
<city isOpen="1" />
</province>
<province>
<city isOpen="0" />
</province>
</regions>

您可能感兴趣的文章:

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wdjyzj.html