首页 > 编程 > JavaScript > 正文

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

2019-11-20 12:28:42
字体:
来源:转载
供稿:网友

本文实例讲述了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程序设计有所帮助。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表