(function(){ /** 获取对象 */ var $ = function(id){ return typeof id == "string" ? document.getElementById(id):id; }; /** 绑定事件流 */ var bind = function(obj, eventName, funcionName){ if(obj.addEventListener){ obj.addEventListener(eventName, funcionName,false); }else if(obj.attachEvent) { obj.attachEvent("on" + eventName, funcionName); }else{ obj["on" + eventName] = funcionName; } }; var Cascading = function(ids){ /** 存放级联id,数据类型为数组(字符串或者select对象),前一个为后一个的父节点 */ for(var i=0,len=ids.length;i<len;i++){ var select = $(ids[i]); Array.prototype.push.call(this, select); /** 设置初始下标为0 */ this.indexes.push(0); /** 追加事件 */ bind(select, "change", this._change(select, i)); } }; Cascading.prototype = { /** 级联深度 */ length:0, /** 级联选择下标 */ indexes:[], /** 默认--- 请选择 ---为首项占位符 */ _defaultSpace:"--- \u8bf7\u9009\u62e9 ---", /** 级联数据存放 */ _buffer:null, _opt:function(name, code){ return new Option(name, code); }, _change:function(select, index){ /** 延长自身作用域 */ var tmp = this; return function(){ tmp.indexes[index] = select.selectedIndex; /** 超过级联深度 */ if(index>=tmp.length-1) return; var data = tmp._buffer; /** 查找需要刷入的数据 */ for(var i=0;i<=index;i++){ var idx = tmp.indexes[i]; /** 去除请选择的级联 */ if(idx==0) { data = null;//清除 break; } data = data[idx-1].children; if(!data) break; } /** 刷新下一个级联 */ tmp._flush(index+1, data); /** 清除后续级联值 */ tmp._reset(index+2); } }, setData:function(jsonArray){ /** * 数据格式为jsonArray,支持多级级联,以省市县为例, * 示例:[ * {"code":"01","name":"北京","children":[{"code":"0001","name":"北京市","children":[{"code":"0000001","name":"朝阳"},{"code":"0000002","name":"海淀"},{"code":"0000003","name":"西城"}]}]}, * {"code":"02","name":"四川","children":[{"code":"0002","name":"成都市","children":[{"code":"0002001","name":"金牛"},{"code":"0002002","name":"成华"},{"code":"0002003","name":"青阳"}]}, * {"code":"0003","name":"乐山市","children":[{"code":"0003001","name":"市中区"},{"code":"0003002","name":"五通桥"},{"code":"0003003","name":"测试区"}]}]} * ] */ this._buffer = jsonArray; return this; }, _setRoot:function(){ /** 最大父节点的初始化 */ var root = this[0]; /** 填充数据 */ this._fillData(root, this._buffer); }, _fillData:function(select, data){ /** 填充级联数据 */ var opts = select.options; /** 设置占位选项 */ opts[0] = this._opt(this._defaultSpace, "-1"); opts[0].selected = true; /** 无值则不填充相应数据 */ if(!data) return; for(var i=0,len=data.length;i<len;i++){ opts[opts.length] = this._opt(data[i].name, data[i].code); } }, _flush:function(index, data){ var s = this[index]; /** 清除原有数据 */ s.innerHTML = ""; this._fillData(s, data); }, _reset:function(index){ /** 重置后续级联数据 */ for(;index<this.length;index++){ this[index].innerHTML = ""; var opts = this[index].options; opts[0] = this._opt(this._defaultSpace, "-1"); } }, setSpace:function(space){ this._defaultSpace = space; return this; }, init:function(){ /** 初始化根节点 */ this._setRoot(); /** 重置后续节点 */ this._reset(1); } }; /** 暴露调用 */ window.CCD = function(ids){ if ( ids && ids instanceof Array && ids.length>=2 ){ return new Cascading(ids); } }; })()