1. 程式人生 > >省市縣三級聯動(與後臺僅互動一次)

省市縣三級聯動(與後臺僅互動一次)

<script type="text/javascript">


    // 省市縣三級假資料,實際開發中,該變數的值可改為AJAX獲取
    var area = "[{id:101,name:'北京',pid:0},{id:102,name:'山東',pid:0},{id:103,name:'河北',pid:0},{id:201,name:'海淀區',pid:101},{id:202,name:'豐臺區',pid:101},{id:203,name:'朝陽區',pid:101},{id:210,name:'濟南',pid:102},{id:211,name:'青島',pid:102},{id:212,name:'煙臺',pid:102},{id:220,name:'石家莊',pid:103},{id:221,name:'邯鄲',pid:103},{id:222,name:'邢臺',pid:103},{id:301,name:'長清',pid:210},{id:302,name:'市中區',pid:210},{id:303,name:'章丘',pid:210},{id:304,name:'市南區',pid:211},{id:305,name:'黃島',pid:211},{id:306,name:'平度',pid:211}]";

    // 將字串轉成JSON物件
    var areaJson = eval("(" + area + ")");

    // 頁面載入完成後執行的方法
    $(function(){

        renderProvince();

        var selectedProvinceId = $("#provinceSelect").val();

        renderCity(selectedProvinceId);

        var selectedCityeId = $("#citySelect").val();

        renderCountry(selectedCityeId);
    });


    // 渲染【省】下拉框
    function renderProvince(){

        for(var i=0; i<areaJson.length; i++){

            if(areaJson[i].pid == 0){
                var provinceOption = "<option value="+areaJson[i].id+">"+areaJson[i].name+"</option>";
                $("#provinceSelect").append(provinceOption);
            }
        }
    }

    // 渲染【市】下拉框
    function renderCity(provinceId){
        
        $("#citySelect").empty();

        for(var i=0; i<areaJson.length; i++){

            if(areaJson[i].pid == provinceId){
                var cityOption = "<option value="+areaJson[i].id+">"+areaJson[i].name+"</option>";
                $("#citySelect").append(cityOption);
            }
        }
    }

    // 渲染【縣】下拉框
    function renderCountry(cityId){
        
        $("#countrySelect").empty();
        for(var i=0; i<areaJson.length; i++){

            if(areaJson[i].pid == cityId){
                var countryOption = "<option value="+areaJson[i].id+">"+areaJson[i].name+"</option>";
                $("#countrySelect").append(countryOption);
            }
        }
    }

    // 重新整理【市】和【縣】兩級下拉框
    function refreshCitySelect(){

        var selectedProvinceId = $("#provinceSelect").val();

        renderCity(selectedProvinceId);

        var selectedCityeId = $("#citySelect").val();

        renderCountry(selectedCityeId);
    }

    // 重新整理【縣】下拉框
    function refreshCountrySelect(){
                
        var selectedCityeId = $("#citySelect").val();

        renderCountry(selectedCityeId);
    }

</script>

<body>

<div>省市縣三級聯動</div>
<div id="luckyName">

    <select id="provinceSelect" onchange="refreshCitySelect()"></select>

    <select id="citySelect" onchange="refreshCountrySelect()"></select>

    <select id="countrySelect"></select>★★★★★
    
</div>

</body>