1,所谓联动效果,是指出发父级的数据变化时,会影响到关联性子级数据元素的变化。
下面是造的省市的数据:
rush:js;">
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节点:
rush:js;">
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事件:
rush:js;">
pro.onchange = function(){
console.log(this);
var ct = city[this.value],ctLen = ct.length,ct
Box = [];
c.innerHTML = "";
/*
添加城市*/
for(var j = 0;j < ctLen;j++){
ct
Box.push({
"text" : ct[j],"value": ct[j]
});
}
addOptions(c,ct
Box);
}
全部JavaScript代码:
rush:js;">
var linkDatas = {
provinces:[
{
"code":"0",6:[
"其他"
]
}
};
function addOptions(target,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],pro
Box = [];
/*
添加省份*/
for(var i = 0;i < provinces.length;i++){
pro
Box.push({
"text" : provinces[i].name,"value": provinces[i].code
})
}
addOptions(pro,pro
Box);
/*初始化城市*/
addOptions(c,[{
"text" : initCity,"value": initCity
}]);
/*
添加联动事件*/
pro.onchange = function(){
console.log(this);
var ct = city[this.value],ct
Box);
}
}
var provinces = document.getElementById('provinces'),citys = document.getElementById('citys');
provincesCitysLink(provinces,citys);