本帖最后由 honcur 于 2012-11-26 21:50:10 编辑 刚刚学习js,对于它的设计思想更是不知道了,写的代码自己都看着很烂。需求如图
// JavaScript Document
function parseXML(filename){
var xmlDoc;
try { //Internet Explorer
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
} catch (e) {
try { //Firefox, Mozilla, Opera, etc.
xmlDoc = document.implementation.createDocument("", "", null);
} catch (e) { }
}
//关闭异步加载,这样确保在文档完全加载之前解析器不会继续脚本的执行。
xmlDoc.async=false;
//解析器加载名为 "xxx.xml" 的 XML 文档、
xmlDoc.load(filename);
return xmlDoc;
}
var nodes = parseXML('china.xml').getElementsByTagName("province");//得到所有province节点
//province对象
function Province(city,name,id) {
this.name = name;
this.city = city;
this.id=id;
this.toString = function () {
return this.name+"|"+this.city+"|"+"-->"+this.id;
}
}
//city对象
function City(province,name,id) {
this.name = name;
this.province = province;
this.id = id;
this.toString = function () {
return this.name+"|";
}
}
//让一个documents的节点转化成的provine的节点对象
function listprovince() {
var arr = new Array();
for(var i=0;i<nodes.length;i++) {
var province = new Province();
province.name = nodes[i].getAttribute('name');
province.id = i;
var nodess = nodes[i].getElementsByTagName('city');
var citys = new Array();
for(var j=0;j<nodess.length;j++) {
var city = new City(province,"");
city.id = i+"_"+j;
city.name = nodess[j].firstChild.data;
citys[j] = city;
}
province.city = citys;
arr[i]=province;
}
return arr;
}
//将一个op对象添加到指定的select下面
function toOption(op2s,des) {
for(var i=0;i<op2s.length;i++) {
var op = document.createElement("option");
op.setAttribute("value",op2s[i].id);
var name = op2s[i].name;
op.setAttribute("name",name);
op.innerHTML = name;
des.appendChild(op);
}
}
//操作china.xml文件
function test() {
var provinces = listprovince();
var sele = document.getElementById("province");
var sele1 = document.getElementById("city");
var id = sele.value;
id=id?id:0;
sele.innerHTML = null;
toOption(provinces,sele);
sele.value = id;
var id1 = sele1.value;
sele1.innerHTML = "<option> 请选择</option>";