select下拉菜单多级级联效果代码实例

快乐打工仔 分类:实例代码

使用select下拉菜单经常制作多级级联效果,本章节就以一个省市地区三级级联效果做一下演示。

代码实例如下:

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="author" content="http://www.pipipi.net/" />
  <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>

回复

我来回复
  • 暂无回复内容