简单的三级联动练习
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{margin: 0;padding: 0;}
</style>
</head>
<body>
<div id="box">
<select name="" id="sh" style="width: 100px;" onchange="ch(this)">
<option value="">请选择</option>
</select>
<select name="" id="si" style="width: 100px" onchange="ch1(this)">
<option value="">请选择</option>
</select>
<select name="" id="qu" style="width: 100px">
<option value="">请选择</option>
</select>
</div>
</body>
<script type="text/javascript">
var sheng = document.getElementById("sh");
var shi = document.getElementById("si");
var qu = document.getElementById("qu");
var shengArr = ["北京","上海","甘肃"];
var shiArr = [
["海淀","丰台","大兴"],
["浦东","高区","开发区"],
["天水","白银","兰州"]
];
var quArr = [
[
["海淀1","海淀2","海淀3"],
["丰台1","丰台2","丰台3"],
["大兴1","大兴2","大兴3"]
],
[
["浦东1","浦东2","浦东3"],
["高区1","高区2","高区3"],
["开发区1","开发区2","开发区3"]
],
[
["天水1","天水2","天水3"],
["白银区","平川区","靖远县"],
["西固","西关","东关"]
]
];
//先设置省的值
for (var i = 0; i < shengArr.length; i++) {
var s = new Option(shengArr[i], i);
sheng.options.add(s);
}
//设置一个省的公共下标
var index = -1;
function ch(obj){
if (obj.value == -1) {
//options 集合可返回包含 <select> 元素中所有 <option> 的一个数组
qu.options.length = 0;
shi.options.length = 0;
}
//获取值
var val = obj.value;
index = obj.value;
//获取市
var cs = shiArr[val];
//获取默认区
var as = quArr[val][0];
//先清空市和区
shi.options.length = 0;
qu.options.length = 0;
for (var i = 0; i < cs.length; i++) {
//第一个参数是option的文本值,第二个参数是option的value值
var op = new Option(cs[i], i);
shi.options.add(op);
}
for (var i = 0; i < as.length; i++) {
var op = new Option(as[i], i);
qu.options.add(op);
}
}
function ch1(obj){
//selectedIndex 属性可设置或返回下拉列表中被选选项的索引号
var val = obj.selectedIndex;//获取value值
var as = quArr[index][val];//
console.log("ddd");
qu.options.length = 0;
for (var i = 0; i < as.length; i++) {
var op = new Option(as[i], i);
qu.options.add(op);
}
}
</script>
</html>
下面是我的公众号,大家可以关注一下,可以一起学习,一起进步: