javascript中的省市级联效果

时间:2024-05-24 13:04:56

学习javascript的时候都遇到过这样的需求,不仅是省市,还有其他的一些场景,看看关键的代码有哪些吧。

 <head runat="server">
<title>省市级联效果</title>
<script type="text/javascript">
var cityList = [{ "province": "四川省", "city": ["成都", "内江", "绵阳", "眉山", "自贡"] },
{ "province": "山东省", "city": ["济南", "青岛", "德州", "淄博", "泰安", "菏泽", "临沂"] },
{ "province": "浙江省", "city": ["杭州", "金华", "绍兴", "温州", "衢州"] },
{ "province": "海南省", "city": ["海口", "三亚", "儋州", "东方", "五指山"] }, ]; window.onload = function () {
var province = document.getElementById("province");
//绑定事件
province.onchange = selectCity;
}; function selectCity() {
//城市
var city = document.getElementById("city");
//先清空数据
if (city != null) {
city.options.length = 0;
} //省份
var province = document.getElementById("province");
//获取选中省份的索引
var provinceSelectedIndex = province.selectedIndex;
//获取选中省份的项
var provinceSelectedOption = province.options[provinceSelectedIndex]; //遍历城市列表
for (var i = 0; i < cityList.length; i++) {
if (cityList[i].province == provinceSelectedOption.innerText) {
for (var j = 0; j < cityList[i].city.length; j++) {
//创建节点
var optionNew = document.createElement("option");
//为节点属性赋值
optionNew.innerText = cityList[i].city[j];
//添加节点
city.appendChild(optionNew);
}
}
}
} </script>
</head>
<body>
<form id="form1" runat="server">
<div>
<select id="province" style="width: 200px;">
<option selected="selected">--请选择--</option>
<option>四川省</option>
<option>山东省</option>
<option>浙江省</option>
<option>海南省</option>
</select>
<select id="city" style="width: 200px;">
</select>
</div>
</form>
</body>

效果图:

javascript中的省市级联效果

2015年2月2日,改成代码版,原来是图片版。