js+xml 生成级联下拉框代码,需要的朋友可以参考下
Javascript 是一种由 Netscape 的 LiveScript 发展而来的原型化继承的基于对象的动态类型的区分大小写的客户端脚本语言,主要目的是为了解决服务器端语言,比如 Perl,遗留的速度问题,为客户提供更流畅的浏览效果。
需要默认选中时,定义一个变量 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 name="湖北">
- <city id="1" name="武汉" isOpen="1" />
- <city id="2" name="黄冈" isOpen="1" />
- <city id="19" name="襄樊" isOpen="1" />
- <city id="22" name="鄂州" isOpen="0" />
- <city id="24" name="黄石" isOpen="1" />
- </province>
- <province name="重庆">
- <city id="23" name="重庆" isOpen="0" />
- </province>
- </regions>
来源: