效果图:
我们可以用JavaScript或者Jquery来实现这个功能。
首先是JavaScript方法:
页面代码为:
<body>
<center>
<div style="vertical-align: middle; border: 2px solid blueviolet; width: 1000px;height: 400px;">
<center>
<form name="form1">
<select id="province" οnchange="getCity()">
<option>请选择</option>
<option>河南</option>
<option>江苏</option>
<option>湖北</option>
</select>
<select id="city">
<option value="0">请选择</option>
</select>
</form>
</center>
</div>
</center>
</body>
实现功能代码:
(1)定义一个数组
var city = [["许昌","平顶山","南阳","开封","郑州","商丘"],
["无锡","苏州","南京","南通","徐州","常州"],["武汉","襄阳","黄石","宜昌","荆门","孝感"],];
(2)把逻辑写进getCity方法
function getCity() {
//省
var setProvince = document.form1.province;
//市
var setCity = document.form1.city;
//城市数组
//selectedIndex是数组的当前选项的索引值(0-n),没选中是-1
//selectedIndex对应列表中该位置显示的项
var provinceCity = city[setProvince.selectedIndex - 1];
//清下拉框
setCity.length = 1;
//将城市数组中的值插入城市下拉框
for (i = 0; i < provinceCity .length; i++) {
setCity[i+1] = new Option(provinceCity[i]);
}
}
接下来是jquery的方法:
页面代码为:
<body>
<div style="border: 2px solid blueviolet; width: 1000px;height: 400px;margin-left: 200px">
<table align="center">
<tr>
<td>
<select>
<option>请选择省份</option>
</select>
<select>
<option>请选择城市</option>
</select>
</td>
</tr>
</table>
</div>
</body>
实现功能代码为:
$(function(){
var provinces='{"江苏":["南京","南通"],"河南":["南阳","许昌"]}';
var citys=eval('('+provinces+')');
for (var i in citys) {
$("select:eq(0)").append("<option>"+i+"</option>");
}
$("select:eq(0)").change(function(){
var province=$(this).val();
$("select:eq(1)").html('<option>请选择城市</option>');
for(var j in citys[province]){
var city=citys[province][j];
$("select:eq(1)").append('<option>'+city+'</option>');
}
});
});
注意:别忘了最重要的一行代码
<script src="jquery-3.3.1.js"></script>