引入
通过JS操作DOM元素对象,实现三级联动,效果如图所示。
js代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>三级联动</title>
</head>
<body>
<select name="province" id="province" onchange="changeP(this)">
<option value="-1">--请选择省--</option>
</select>
<select name="city" id="city" onclick="changeC(this)">
<option value="">--请选择市--</option>
</select>
<select name="area" id="area">
<option value="">--请选择区--</option>
</select>
</body>
<script>
let arrP = ['湖南省', '湖北省', '广东省'];
let arrC = [
['长沙', '株洲', '吉首', '常德', '张家界'],
['武汉', '襄阳', '随州', '宜昌', '荆州'],
['广州', '台山', '佛山', '中山', '云浮']
];
let arrA = [
[
['长沙1', '长沙2', '长沙3', '长沙4', '长沙5'],
['株洲1', '株洲2', '株洲3', '株洲4', '株洲5'],
['吉首1', '吉首2', '吉首3', '吉首4', '吉首5'],
['常德1', '常德2', '常德3', '常德4', '常德5'],
['张家界1', '张家界', '张家界3', '张家界4', '张家界5']
],
[
['武汉1', '武汉', '武汉3', '武汉4', '武汉5'],
['襄阳1', '襄阳2', '襄阳3', '襄阳4', '襄阳5'],
['随州1', '随州2', '随州4', '随州4', '随州5'],
['宜昌1', '宜昌2', '宜昌3', '宜昌4', '宜昌5'],
['荆州1', '荆州2', '荆州3', '荆州4', '荆州5']
],
[
['广州1', '广州2', '广州', '广州4', '广州5'],
['台山1', '台山2', '台山3', '台山4', '台山5'],
['佛山1', '佛山2', '佛山3', '佛山4', '佛山5'],
['中山1', '中山2', '中山3', '中山4', '中山5'],
['云浮1', '云浮2', '云浮3', '云浮4', '云浮5']
],
];
//添加省选择
let province = document.getElementById('province');
let area = document.getElementById('area');
let city = document.getElementById('city');
for (let i in arrP) {
let op = document.createElement('option');
op.setAttribute('value', arrP[i]);
op.innerText = arrP[i];
province.appendChild(op);
}
//省改变函数
function changeP(provinceH) {
let arr = arrC[provinceH.selectedIndex - 1];
//让省份只留第一项
if (typeof arr != 'undefined') {
city.options.length = 0;
for (let index in arr) { //创建Option对象可以直接设置文本内容和值
city.options.add(new Option(arr[index], arr[index]));
}
changeC(city);
} else {
city.innerHTML = "<option value='-1'>--请选择市--</option>";
area.innerHTML = "<option value='-1'>--请选择区--</option>";
}
}
//区改变函数
function changeC(cityH) {
//防止为undefined时取数组值报错
if (typeof arrA[province.selectedIndex - 1] != 'undefined') {
let arr = arrA[province.selectedIndex - 1][cityH.selectedIndex];
//让省份只留第一项
area.options.length = 0;
for (let index in arr) { //创建Option对象可以直接设置文本内容和值
area.options.add(new Option(arr[index], arr[index]));
}
}
}
</script>
</html>