需要默认选中时,定义一个变量 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 // 获取省节点的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;jif(citys[j].getAttribute("id")==cityId){
opt.selected="selected";
for ( var j = 0; 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 // 获取省节点的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 // 创建一个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结构