在日常项目开发阶段经常见到下拉框二级联动效果,尤其是涉及地区、品种等有多级选项时。比如说:常见的省市联动下拉框,在选择省份时,城市列表也会更随改变。
思路:
1,所谓联动效果,是指出发父级的数据变化时,会影响到关联性子级数据元素的变化。
下面是造的省市的数据:
var linkDatas = {provinces:[{"code":"0","name":"请选择"},{"code":"1","name":"北京"},{"code":"2","name":"天津"},{"code":"3","name":"河北"},{"code":"4","name":"湖北"},{"code":"5","name":"广东"},{"code":"6","name":"其他"}],citys:{0:["请选择"],1:["朝阳区","海淀区","东城区","西城区","房山区","其他"],2:["天津"],3:["沧州","石家庄","秦皇岛","其他"],4:["武汉市","宜昌市","襄樊市","其他"],5:["广州市","深圳市","汕头市","佛山市","珠海市","其他"],6:["其他"]}};
2,根据数据动态生成option节点:
function addOptions(target,options){var optionEle = null,target = target,option = options,optionLen = options.length;for(var i = 0;i < optionLen;i++){optionEle = document.createElement('option');optionEle.value = option[i].value;optionEle.text = option[i].text;target.options.add(optionEle);}}
3,根据上述省市数据,其中code代表“省级”指向“城市”的标识符,当省级的数据变更时,出发change事件:
pro.onchange = function(){console.log(this);var ct = city[this.value],ctLen = ct.length,ctBox = [];c.innerHTML = ""; for(var j = 0;j < ctLen;j++){ctBox.push({"text" : ct[j],"value": ct[j]});}addOptions(c,ctBox);}
HTML代码:
<div class="content"><h3>下拉框联动效果</h3><p>省份:<select name="provinces" id="provinces"></select></p><p>市:<select name="citys" id="citys"></select></p></div>
全部JavaScript代码:
var linkDatas = {provinces:[{"code":"0","name":"请选择"},{"code":"1","name":"北京"},{"code":"2","name":"天津"},{"code":"3","name":"河北"},{"code":"4","name":"湖北"},{"code":"5","name":"广东"},{"code":"6","name":"其他"}],citys:{0:["请选择"],1:["朝阳区","海淀区","东城区","西城区","房山区","其他"],2:["天津"],3:["沧州","石家庄","秦皇岛","其他"],4:["武汉市","宜昌市","襄樊市","其他"],5:["广州市","深圳市","汕头市","佛山市","珠海市","其他"],6:["其他"]}};function addOptions(target,options){var optionEle = null,target = target,option = options,optionLen = options.length;for(var i = 0;i < optionLen;i++){optionEle = document.createElement('option');optionEle.value = option[i].value;optionEle.text = option[i].text;target.options.add(optionEle);}}function provincesCitysLink(pro,c){var LD = linkDatas,provinces = LD.provinces,city = LD.citys,initCity = city[0],proBox = [];for(var i = 0;i < provinces.length;i++){proBox.push({"text" : provinces[i].name,"value": provinces[i].code})} addOptions(pro,proBox);addOptions(c,[{"text" : initCity,"value": initCity}]);pro.onchange = function(){console.log(this);var ct = city[this.value],ctLen = ct.length,ctBox = [];c.innerHTML = ""; for(var j = 0;j < ctLen;j++){ctBox.push({"text" : ct[j],"value": ct[j]});}addOptions(c,ctBox);}}var provinces = document.getElementById('provinces'),citys = document.getElementById('citys');provincesCitysLink(provinces,citys);