/* @ name:城市联动插件 @ author:前端老徐 @ date:2016-3-21 */ ;(function(w){ function fn(){ this.node={ prov:document.getelementbyid('prov'), city:document.getelementbyid('city'), area:document.getelementbyid('area') } this.data=null; this.def={prov:0,city:0,area:0} this.nodata=[{id:'',name:'市/区'}]; } //初始化 fn.prototype.init=function(opt,d1,d2,d3){ var _self=this; //默认值 _self.def.prov=d1?d1:0 _self.def.city=d2?d2:0 _self.def.area=d3?d3:0 //节点 _self.node.prov=opt.prov _self.node.city=opt.city _self.node.area=opt.area; //获取省市 this.getprov(); } //创建表单 fn.prototype.create=function(data,def,key_id,key_name){ var fra=document.createdocumentfragment(); for(x in data){ var opt=document.createelement('option'); opt.appendchild(document.createtextnode(data[x][key_name])) opt.setattribute('value',data[x][key_id]); opt.setattribute('data-index',x); if(data[x][key_id]==def){ opt.selected=true; } fra.appendchild(opt); } return fra; } //获取省市 fn.prototype.getprov=function(){ var _self=this; var xmlhttp=new xmlhttprequest(); xmlhttp.open("get","/api/common/address.php?action=getcitylist",true); xmlhttp.send(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readystate==4 && xmlhttp.status==200){ var data=(eval('('+xmlhttp.responsetext+')')); if(data.code==1000){ //缓存数据 _self.data=data.data; //创建dom _self.node.prov.appendchild(_self.create(data.data,_self.def.prov,'province_id','provincename')); //绑定切换 _self.node.prov.onchange=function(){ _self.getcity.call(_self); } //获取城市 _self.getcity(); } } } } //获取市 fn.prototype.getcity=function(){ var _self=this; if(_self.node.prov.value){ var index=_self.node.prov.options[_self.node.prov.selectedindex].getattribute('data-index'); _self.node.city.innerhtml=''; _self.node.city.appendchild(_self.create(_self.data[index].citylist,_self.def.city,'city_id','cityname')); //绑定切换 _self.node.city.onchange=function(){ _self.getarea.call(_self); } //获取区县 _self.getarea(); }else{ _self.node.city.innerhtml=''; _self.node.city.appendchild(_self.create(_self.nodata,_self.def.city,'id','name')); if(_self.node.area){ _self.node.area.innerhtml=''; _self.node.area.appendchild(_self.create(_self.nodata,_self.def.area,'id','name')); } } } //获取区县 fn.prototype.getarea=function(){ var _self=this; if(!_self.node.area){return} var xmlhttp=new xmlhttprequest(); xmlhttp.open("get","/api/common/address.php?action=getdistrictlist&city="+_self.node.city.value,true); xmlhttp.send(); xmlhttp.onreadystatechange=function(){ if (xmlhttp.readystate==4 && xmlhttp.status==200){ var data=(eval('('+xmlhttp.responsetext+')')); if(data.code==1000){ _self.node.area.innerhtml=''; _self.node.area.appendchild(_self.create(data.data,_self.def.area,'id','district_name')); }else{ //alert(data.info); if(_self.node.area){ _self.node.area.innerhtml=''; _self.node.area.appendchild(_self.create(_self.nodata,_self.def.area,'id','name')); } } } } }, w.cityselect=fn })(window);