<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>省市级联动</title>
</head>
<script>
var provinces=["请选择省份","江苏省","浙江省","江西省","海南省"];
var citys=[
["请选择城市"],
["南京市","无锡市","徐州市","常州市","苏州市","南通市","连云港市","淮安市","盐城市","扬州市","镇江市","泰州市","宿迁市"],
["杭州市","宁波市","温州市","绍兴市","湖州市","嘉兴市","金华市","衢州市","台州市","丽水市","舟山"],
["南昌市","九江市","上饶市","抚州市","宜春市","吉安市","赣州市","景德镇","萍乡市","新余市","鹰潭市"],
["海口市","三亚市","三沙市","儋州市"]
];
var index=0;
window.onload = function (){
var province = document.getElementById("province");
var city = document.getElementById("city");
//创建好后加入到列表中
for(var i in provinces)
{
var option = document.createElement("option");
option.text=provinces[i];
option.value=provinces[i];
province.appendChild(option);
}
var option = document.createElement("option");
option.text=citys[index];
option.value=citys[index];
city.appendChild(option);
}
var selectedIndex =0;
function changeProvince(selectedIndex){
this.selectedIndex = selectedIndex;
var city=document.getElementById("city");
city.options.length=0;
for(var i in citys[selectedIndex])
{
var option = document.createElement("option");
option.text=citys[selectedIndex][i];
option.value=citys[selectedIndex][i];
city.appendChild(option);
}
}
//添加省
function addProvince(){
//获取省级输入内容
var province_input=document.getElementById("province_input").value;
//末尾追加
provinces.push(province_input);
var province = document.getElementById("province");
//最后一位索引
//alert(provinces.length-1);
//创建好后加入到列表中
var option = document.createElement("option");
option.text=provinces[provinces.length-1];
option.value=provinces[provinces.length-1];
province.appendChild(option);
}
//添加城市
function addCity(){
//获取市级输入内容
var city_input=document.getElementById("city_input").value;
//alert("输入内容:"+city_input);
//alert(citys.length);
//citys.push([city_input]);
//alert("索引:"+citys.length-1);
//alert(selectedIndex);
var city=document.getElementById("city");
city.options.length=0;
if( selectedIndex >= 5){
//进行数组初始化
citys.push([]);
//进行数组赋值
citys[selectedIndex].push([city_input]);
}else{
//当索引小于5,直接赋值
citys[selectedIndex].push([city_input]);
}
for(var i in citys[selectedIndex])
{
var option = document.createElement("option");
option.text=citys[selectedIndex][i];
option.value=citys[selectedIndex][i];
city.appendChild(option);
}
}
</script>
<body>
<div id="">
选择省份:
<select id="province" name="province" onchange="changeProvince(this.selectedIndex)">
</select>
城市:
<select id="city" name="city">
</select>
</div>
<table>
<tr>
<td><input type="text" name="province_input" id="province_input" value="" placeholder="请输入省份"/></td>
<td><input type="button" name="province_add" id="" value="添加省份" onclick="addProvince()"/></td>
</tr>
<tr>
<td><input type="text" name="city_input" id="city_input" value="" placeholder="请输入城市"/></td>
<td><input type="button" name="city_add" id="" value="添加城市" onclick="addCity()" /></td>
</tr>
</table>
</body>
</html>