普通的三级联动
html:
<body>
省:<select id="s1">
<option>—请选择—</option>
</select>
市:<select id="s2">
<option>—请选择—</option>
</select>
区:<select id="s3">
<option>—请选择—</option>
</select>
</body>
js:1、先用json数据模拟后台数据并获取数据
2、再获取select并添加事件onchange
3、在每次选择前清空上次选择
<script>
//用 json 数据模拟后台数据
var city = [
{
"id": 10001,
"name": "陕西省",
"child": [
{
"id": 100011,
"name": "西安市",
"child": [
{
"id": 100011,
"name": "高新区"
},
{
"id": 100011,
"name": "未央区"
}
]
},
{
"id": 100012,
"name": "宝鸡市",
"child": [
{
"id": 100011,
"name": "高新区"
},
{
"id": 100011,
"name": "成仓区"
}
]
}
]
},
{
"id": 10002,
"name": "甘肃省",
"child": [
{
"id": 100021,
"name": "兰州市",
"child": [
{
"id": 100021,
"name": "兰州区1"
},
{
"id": 100021,
"name": "兰州区2"
}
]
},
{
"id": 100022,
"name": "酒泉市",
"child": [
{
"id": 100021,
"name": "酒泉区1"
},
{
"id": 100021,
"name": "酒泉区2"
}
]
}
]
}
]
var s1 = document.getElementById("s1");
var s2 = document.getElementById("s2");
var s3= document.getElementById("s3");
for (var i = 0; i < city.length; i++) {
var opt = new Option(city[i].name,i);
s1.appendChild(opt);
}
//添加事件
var cityname=null;
s1.onchange=function (){
//s2做个清除
s2.options.length=1;
//s3做个清除
s3.options.length=1;
var index=this.value;
cityname=city[index].child;
for(var i=0;i<cityname.length;i++)
{
var opt=new Option(cityname[i].name,i);
s2.appendChild(opt);
}
}
s2.onchange=function (){
//s3做个清除
s3.options.length=1;
var index=this.value;
var qu=cityname[index].child;
for(var i=0;i<qu.length;i++)
{
var opt=new Option(qu[i].name,i);
s3.appendChild(opt);
}
}
</script>