<!DOCTYPE html>
<html>
<head>
<title>js_select.html</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<!--<link rel="stylesheet" type="text/css" href="./styles.css">-->
<script type="text/javascript">
window.onload = function() {
// 采用数组来存放 js原生格式,二级联动
var provinces = [ {
id : '1',
name : '北京',
city : [ '海淀区', '朝阳区', '大兴区' ]
}, {
id : '2',
name : '天津',
city : [ '北辰区', '和平区', '虹桥区' ]
}, {
id : '3',
name : '上海',
city : [ 'A区', 'B区', 'C区' ]
}, {
id : '4',
name : '重庆',
city : [ 'WW区', 'EE区', 'TT区' ]
} ];
// 页面加载时,显示省份
var domProvinces = document.getElementById("province");
// 遍历省份集合
for ( var i = 0; i < provinces.length; i++) {
// 获取具体省份对象
var pro = provinces[i];
// 创建元素节点
var option = document.createElement("option");
option.setAttribute("value", pro.id); //为option添加value属性
var textNode = document.createTextNode(pro.name); //创建文本节点
option.appendChild(textNode);
domProvinces.appendChild(option);
}
//当省份发生变化时,把相应的市区显示给用户
var domcity = document.getElementById("city");
domProvinces.onchange = function() {
//清除数据
domcity.length = 1;
for ( var i = 0; i < provinces.length; i++) {
//获取具体省份对象
var dpro = provinces[i];
if (this.value == dpro.id) {
var city = dpro.city;
for ( var j = 0; j < city.length; j++) {//创建元素节点
var doption = document.createElement("option");
//创建文本节点
var dtextNode = document.createTextNode(city[j]);
doption.appendChild(dtextNode);
//把创建的option节点添加到id=city的select中
domcity.appendChild(doption);
}
break;
}else{
continue;
}
}
}
}
</script>
</head>
<body>
<br>
<select id="province">
<option value="-1">请选择省份</option>
</select>
<select id="city">
<option value="-1">请选择市区</option>
</select>
</body>
</html>
转载于:https://www.cnblogs.com/zhangguoliang521/archive/2013/03/13/3057483.html