这篇文章主要介绍了javascript基于DOM实现省市级联下拉框的方法,可实现选择省份后出现对应城市下拉框选项的功能,非常具有实用价值,需要的朋友可以参考下
本文实例讲述了javascript基于DOM实现省市级联下拉框的方法。分享给大家供大家参考。具体实现方法如下:
- <html xmlns="http://www.w3.org/1999/xhtml">
- <head>
- <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
- <title>省市级联下拉框</title>
- <script type="text/javascript">
- var provs = { "江西省": ["南昌市", "景德镇", "九江", "鹰潭", "萍乡", "新馀", "赣州", "吉安", "宜春", "抚州", "上饶"],
- "福建省": ["福州", "厦门", "莆田", "三明", "泉州", "漳州", "南平", "龙岩", "宁德"],
- "河北省": ["石家庄", "邯郸", "邢台", "保定", "张家口", "承德", "廊坊", "唐山", "秦皇岛", "沧州", "衡水"]
- };
- function loadProv() {
- //加载省份数据
- var prov = document.getElementById("prov");
- for (var key in provs) {
- var provName = key;
- var optProv = document.createElement("option");
- optProv.value = provName;
- optProv.innerText = provName;
- prov.appendChild(optProv);
- }
- }
- function provChange() {
- var prov = document.getElementById("prov");
- var city = document.getElementById("city");
- var provName = prov.value;
- //如果没有选择省份,则把城市下拉框隐藏
- if (provName == "none") {
- city.style.display = "none";
- return;
- }
- else {
- city.style.display = "";
- }
- var citys = provs[provName];
- //city.options.length = 0;
- //用这种方法也可以清空原始列表
- //清空城市的原始数据
- for (var i = city.childNodes.length - 1; i >= 0; i--) {
- var child = city.childNodes[i];
- city.removeChild(child);
- }
- //添加新的城市数据
- for (var i = 0; i < citys.length; i++) {
- var optCity = document.createElement("option");
- optCity.value = citys[i];
- optCity.innerText = citys[i];
- city.appendChild(optCity);
- }
- }
- </script>
- </head>
- <body onload="loadProv()">
- <select id="prov" onchange="provChange()">
- <option value="none">请选择省</option>
- </select>
- <select id="city" style="display:none"></select>
- </body>
- </html>
希望本文所述对大家的javascript程序设计有所帮助。
新闻热点
疑难解答
图片精选