<style type="text/css">
select
{
135px;
}
fieldset dl dd
{
float: left;
margin-left: 20px;
}
fieldset pre
{
100%;
height: 400px;
overflow-y: scroll;
overflow-x: hidden;
}
</style>
<!-- jQuery库文件引入 -->
<script language="javascript" type="text/javascript" src="libs/jquery-1.11.0.min.js"></script>
<script type="text/javascript" language="javascript">
//定义数组,存储省份信息
var province = ["北京"];
//定义数组,存储城市信息
var beijing = ["东城区", "西城区", "海淀区", "朝阳区", "丰台区", "石景山区", "通州区", "顺义区", "房山区", "大兴区", "昌平区", "怀柔区", "平谷区", "门头沟区", "延庆县", "密云县"];
//页面加载方法
$(function () {
//设置省份数据
setProvince();
//设置背景颜色
setBgColor();
});
//设置省份数据
function setProvince() {
//给省份下拉列表赋值
var option, modelVal;
var $sel = $("#selProvince");
//获取对应省份城市
for (var i = 0, len = province.length; i < len; i++) {
modelVal = province[i];
option = "<option value='" + modelVal + "'>" + modelVal + "</option>";
//添加到 select 元素中
$sel.append(option);
}
//调用change事件,初始城市信息
provinceChange();
}
//根据选中的省份获取对应的城市
function setCity(provinec) {
var $city = $("#selCity");
var proCity, option, modelVal;
//通过省份名称,获取省份对应城市的数组名
switch (provinec) {
case "北京":
proCity = beijing;
break;
case "上海":
proCity = shanghai;
break;
}
//先清空之前绑定的值
$city.empty();
//设置对应省份的城市
for (var i = 0, len = proCity.length; i < len; i++) {
modelVal = proCity[i];
option = "<option value='" + modelVal + "'>" + modelVal + "</option>";
//添加
$city.append(option);
}
//设置背景
setBgColor();
}
//省份选中事件
function provinceChange() {
var $pro = $("#selProvince");
setCity($pro.val());
}
//设置下拉列表间隔背景样色
function setBgColor() {
var $option = $("select option:odd");
$option.css({ "background-color": "#DEDEDE" });
}
</script>
<body>
<fieldset>
<legend>中国三级行政单位联动</legend>
<dl>
<dd>
省 份:<select id="selProvince" onchange="provinceChange();"></select>
</dd>
<dd>
市(区):<select id="selCity"></select>
</dd>
</dl>
</fieldset>
</body>