DIV CSS 佈局教程網

 DIV+CSS佈局教程網 >> 網頁腳本 >> JavaScript入門知識 >> 關於JavaScript >> javascript基於DOM實現省市級聯下拉框的方法
javascript基於DOM實現省市級聯下拉框的方法
編輯:關於JavaScript     

本文實例講述了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程序設計有所幫助。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved