js实现区县联动
Posted wyp-ay
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了js实现区县联动相关的知识,希望对你有一定的参考价值。
1. 引入区县联动函数如下,将provinceList中数据改为需要联动的数据信息
var addressInit = function(_cmbProvince, _cmbCity, _cmbArea, _cmbStreet, defaultProvince, defaultCity, defaultArea,defaultStreet) { var cmbProvince = document.getElementById(_cmbProvince); var cmbCity = document.getElementById(_cmbCity); var cmbArea = document.getElementById(_cmbArea); var cmbStreet = document.getElementById(_cmbStreet); function cmbSelect(cmb, str) { for(var i=0; i<cmb.options.length; i++) { if(cmb.options[i].value == str) { cmb.selectedIndex = i; return; } } } function cmbAddOption(cmb, str, obj, num) { var option = document.createElement(‘OPTION‘); cmb.options.add(option); option.innerText = str; option.value = num; option.obj = obj; console.log(num) } function changeProvince() { cmbCity.options.length = 0; cmbCity.onchange = null; if(cmbProvince.selectedIndex == -1)return; var item = cmbProvince.options[cmbProvince.selectedIndex].obj; /**console.log(item)**/ for(var i=0; i<item.cityList.length; i++) { cmbAddOption(cmbCity, item.cityList[i].name, item.cityList[i],item.cityList[i].sleep); } cmbSelect(cmbCity, defaultCity); } for(var i=0; i<provinceList.length; i++) { cmbAddOption(cmbProvince, provinceList[i].name, provinceList[i],provinceList[i].sleep); } cmbSelect(cmbProvince, defaultProvince); changeProvince(); cmbProvince.onchange = changeProvince; } /*用到的所有sleep为自定义属性,sleep可以自定义为指定数据,便于前后端数据交互*/ var provinceList = [ {name:‘全部‘,sleep:‘0‘,//省级 cityList:[//市级 {name:‘全部‘,sleep:‘0‘, areaList:[//区县级 {name:‘全部‘,sleep:‘0‘} ] } ] }, {name:‘陕西省‘,sleep:‘1‘, cityList:[ {name:‘全部‘,sleep:‘0‘, areaList:[ {name:‘全部‘,sleep:‘0‘} ] }, {name:‘西安市‘,sleep:‘1‘, areaList:[ {name:‘全部‘,sleep:‘0‘}, {name:‘鄠邑区‘,sleep:‘1‘}, {name:‘高新区‘,sleep:‘2‘} ] }, {name:‘渭南市‘,sleep:‘2‘, areaList:[ {name:‘全部‘,sleep:‘0‘}, {name:‘大荔县‘,sleep:‘1‘}, {name:‘蒲城县‘,sleep:‘2‘} ] } ] }, {name:‘浙江省‘,sleep:‘2‘, cityList:[ {name:‘全部‘,sleep:‘0‘, areaList:[ {name:‘全部‘,sleep:‘0‘}, {name:‘杭州市‘,sleep:‘1‘}, {name:‘宁波市‘,sleep:‘2‘} ] }, {name:‘杭州市‘,sleep:‘1‘, areaList:[ {name:‘全部‘,sleep:‘0‘}, {name:‘萧山区‘,sleep:‘1‘}, {name:‘富阳区‘,sleep:‘2‘} ] }, {name:‘宁波市‘,sleep:‘2‘, areaList:[ {name:‘全部‘,sleep:‘0‘}, {name:‘江东区‘,sleep:‘1‘}, {name:‘镇海区‘,sleep:‘2‘} ] } ] } ];
2. 在需要联动的页面调用addressInit()联动函数
addressInit(‘省id‘,‘市id‘,‘区县id‘);// 下拉框选择联动
以上是关于js实现区县联动的主要内容,如果未能解决你的问题,请参考以下文章