美文网首页
利用面向过程的方法实现三级联动效果

利用面向过程的方法实现三级联动效果

作者: 深漂浪子 | 来源:发表于2019-06-03 15:17 被阅读0次

话不多说,先上效果图(需要注意的是这里需要引入我本地的省市区数据包)

11.png 222.png 3333.png 4444.png
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            margin: 0;
            padding: 0;
            font-size: 14px;
        }
        #Form{
            margin: 20px auto;
            width: 600px;
            height: 300px;
        }
        select{
            width: 180px;
            height: 30px;
        }
        select>option{
            line-height: 30px;
            text-align: center;
        }
    </style>
    <script src="https://gitee.com/zhongxiaoyou1314520/codes/j860mhlp5ye3o9dsvktw781/raw?blob_name=%E4%B8%89%E7%BA%A7%E5%9F%8E%E5%B8%82%E8%81%94%E5%8A%A8%E4%BB%A3%E7%A0%81%E6%95%B0%E6%8D%AE"></script>
</head>
<body>
<form action="" id="Form">
    <select id="province"></select>省
    <select id="city"></select>市
    <select id="county"></select>县
</form>
<script>
    var data = data;
    console.log(data)
    var province=document.querySelector("#province");
    var city=document.querySelector("#city");
    var county=document.querySelector("#county");

    //初始化
    init();    
    function init() {
        fillProvince();
        fillCity(1);
        fillCounty(1);
    }

    //当省份选择了值的时候,它后面的市和县被跟着替换
    province.onchange=function () {
        var proId=this.value;//把省份值拿到
        fillCity(proId);//把它值跟市挂钩
        var cityId=city.value;
        fillCounty(cityId);

    }

    //当市区选择了值的时候,只需改后面的县
    city.onchange=function () {
        var cityId=city.value;
        fillCounty(cityId);
    }

    //封装一个函数createOption用来在select里面自动生成option
    function createOption(textName,valueId) {
        var option=document.createElement("option");
        //将内容和相应的id值匹配进去
        option.innerHTML=textName;
        option.value=valueId;
        return option;
    }

    //填充省份
   function fillProvince() {
       province.innerHTML='';
       //引进data对象里的省份,填充省份内容和value的ID
       for (var provinces of data.provinceList){
           var option=createOption(provinces.ProName,provinces.ProID);
           province.appendChild(option);
       }
   }
   //填充市区
    function fillCity(proId) {
        city.innerHTML='';
        for (var citys of data.cityList){
            if(citys.ProID==proId){
                var option=createOption(citys.CityName,citys.CityID);
                city.appendChild(option);
            }
        }
    }
    //填充县级
    function fillCounty(cityId) {
        county.innerHTML='';
        for (var countys of data.countyList){
            if(countys.CityID==cityId){
                var option=createOption(countys.DisName,countys.Id);
                county.appendChild(option);
            }
        }
    }
</script>
</body>
</html>

利用遍历的方式,逐个对比省市区所绑定的对应id,然后插入DOM结构实现渲染,省市区数据包(data.js)可在线下载:data.js文

相关文章

网友评论

      本文标题:利用面向过程的方法实现三级联动效果

      本文链接:https://www.haomeiwen.com/subject/rnmcxctx.html