<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<script type="text/javascript">
var provinceArr = ['湖北', '江西', '河南'];
var cityArr = [
['武汉', '黄石', '宜昌', '荆州'],
['南昌', '九江', '赣州'],
['郑州', '洛阳', '开封']
];
/**
* 初始化省份的select
*/
function initProvince() {
var provinceSelect = document.getElementById("province");
for(var i = 0; i < provinceArr.length; i++) {
var opt = document.createElement("option");
opt.innerHTML = provinceArr[i];
opt.value = provinceArr[i];
//将option添加到select
provinceSelect.appendChild(opt);
}
//初始化city的select
changeCity(0);
}
//动态创建option,添加到city
function changeCity(selectedIndex) {
//清除原有的option
var citySelect = document.getElementById("city");
var cityOptions = citySelect.childNodes;
//从高位开始移除(如果从低位移除,会有元素删不掉)
for(var j = cityOptions.length - 1; j >= 0; j--) {
citySelect.removeChild(cityOptions[j]);
}
//1.首先取到省份对应的城市
var cities = cityArr[selectedIndex];
//2.创建option
for(var i = 0; i < cities.length; i++) {
var opt = document.createElement("option");
opt.innerHTML = cities[i];
opt.value = cities[i];
citySelect.appendChild(opt);
}
}
function generateAddress() {
//select.selectedOptions (被选中的所有的option 数组)
var selectedProvince = document.getElementById("province").selectedOptions;
var selectedCity = document.getElementById("city").selectedOptions;
var detailAddress = document.getElementById("detailAddress");
var lastAddress = selectedProvince[0].value + "省" + selectedCity[0].value + "市" + detailAddress.value;
document.getElementById("lastAddress").innerHTML = lastAddress;
}
</script>
</head>
<body>
<!-- select : selectedIndex 被选中的option的下标-->
<select id="province" οnchange="changeCity(this.selectedIndex)">
</select>
<select id="city">
</select>
详细地址:
<input id="detailAddress" placeholder="请输入详细地址" />
<br />
<input type="button" οnclick="generateAddress()" value="生成详细地址" /><span id="lastAddress"></span>
<script type="text/javascript">
initProvince();
</script>
</body>
</html>
js 创建二级菜单
最新推荐文章于 2024-09-03 09:47:06 发布
本文介绍了一个使用JavaScript实现的动态地址选择器。该选择器能够根据用户选择的省份自动更新对应的城市选项。通过简单的HTML结构结合JavaScript编程,实现了省份与城市间的联动效果,并提供了生成完整地址的功能。
摘要由CSDN通过智能技术生成