select下拉選單多級級聯效果程式碼例項

admin發表於2017-04-04

使用select下拉選單經常製作多級級聯效果,本章節就以一個省市地區三級級聯效果做一下演示。

程式碼例項如下:

[HTML] 純文字檢視 複製程式碼
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="author" content="http://www.softwhy.com/" />
  <title>螞蟻部落</title>
  <script>
//宣告省
var pres = ["北京", "上海", "山東"];
//宣告市
var cities = [["東城", "昌平", "海淀"],["浦東", "高區"],["濟南", "青島"]];
var areas =
[
  [
    ["東城1", "東城2", "東城3"],
    ["昌平1", "昌平2", "昌平3"],
    ["海淀1", "海淀2", "海淀3"]
  ],
  [
    ["浦東1", "浦東2", "浦東3"],
    ["高區1", "高區2", "高區3"]
  ],
  [
    ["濟南1", "濟南2"],
    ["青島1", "青島2"]
  ]
]
window.onload=function(){
  //設定一個省的公共下標
  var pIndex = -1;
  var preEle = document.getElementById("pre");
  var cityEle = document.getElementById("city");
  var areaEle = document.getElementById("area");
  //先設定省的值
  for (var i = 0; i < pres.length; i++) {
    var op = new Option(pres[i], i);
    preEle.options.add(op);
  }
  function chg(obj) {
    if (obj.value == -1) {
      cityEle.options.length = 0;
      areaEle.options.length = 0;
    }
    //獲取值
    var val = obj.value;
    pIndex = obj.value;
    //獲取ctiry
    var cs = cities[val];
    //獲取預設區
    var as = areas[val][0];
    //先清空市
    cityEle.options.length = 0;
    areaEle.options.length = 0;
    for (var i = 0; i < cs.length; i++) {
      var op = new Option(cs[i], i);
      cityEle.options.add(op);
    }
    for (var i = 0; i < as.length; i++) {
      var op = new Option(as[i], i);
      areaEle.options.add(op);
    }
  }
  function chg2(obj) {
    var val = obj.selectedIndex;
    var as = areas[pIndex][val];
    areaEle.options.length = 0;
    for (var i = 0; i < as.length; i++) {
      var op = new Option(as[i], i);
      areaEle.options.add(op);
    }
  }
  preEle.onchange=function(){chg(this)}
  cityEle.onchange=function(){chg2(this)}
}
  </script>
</head>
<body>
  省:<select style="width:100px;" id="pre"><option value="-1">請選擇</option></select>
  市:<select style="width: 100px;" id="city"></select>
  區:<select style="width: 100px;" id="area"></select>
</body>
</html>

相關文章