首页 >web前端 >js教程 >javascript基于DOM实现省市级联下拉框的方法

javascript基于DOM实现省市级联下拉框的方法

PHPz
PHPz原创
2016-05-16 15:59:071297浏览

这篇文章主要介绍了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>

【相关教程推荐】

1. JavaScript视频教程
2. JavaScript在线手册
3. bootstrap教程

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn