<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<script>
window.onload = function () {
var city = [
{
name: "江苏",
children: [{name2: "南京", child: ["鼓楼区", "江宁区"]}, {name2: "连云港", child: ["海州区", "赣榆区"]}, {
name2: "苏州市",
child: ["姑苏区", "吴中区"]
}]
},
{
name: "山东",
children: [{name2: "济南", child: ["济南区", "水浒区"]}, {name2: "青岛", child: ["黄岛区", "即墨区"]}, {
name2: "日照",
child: ["东港区", "岚山区"]
}]
}
];
var sheng = document.getElementById("sheng");
var shi = document.getElementById("shi");
var qu = document.getElementById("qu");
//将数组中所有的省份添加到选项中
for (var i = 0; i < city.length; i++) {
var option = document.createElement("option");
sheng.appendChild(option);
option.innerHTML = city[i].name;
}
;
//当省变化时
sheng.onchange = function () {
for (var i = 0; i < city.length; i++) {
shi.length = 1;
if (this.value == city[i].name) {
var arr2 = city[i].children;
for (var j = 0; j < arr2.length; j++) {
var option2 = document.createElement("option");
shi.appendChild(option2);
option2.innerHTML = arr2[j].name2;
}
break;
}
}
};
//当市的选择变化时
shi.onchange = function () {
for (var i = 0; i < city.length; i++) {
var isFind = false;
var arr = city[i].children;
for (var j = 0; j < arr.length; j++) {
qu.length = 1;
if (this.value == arr[j].name2) {
var arrqu = arr[j].child;
for (var z = 0; z < arrqu.length; z++) {
var option = document.createElement("option");
qu.appendChild(option);
option.innerHTML = arrqu[z];
isFind = true;
}
break;
}
}
if (isFind) {
break;
}
}
}
}
</script>
<body>
<select id="sheng" class="xxxx">
<option>--请选择--</option>
</select>
<select id="shi">
<option>--请选择--</option>
</select>
<select id="qu">
<option>--请选择--</option>
</select>
</body>
</html>
最近学习了js,用js写了一个三层城市选择的简单工具,主要用到的只是是听过js来获取元素,添加元素,
并且向标签中添加内容。父元素添加子元素的方法。