1. 程式人生 > >原生js實現三級聯動

原生js實現三級聯動

三級聯動 chan 學習 initial ble ont view document chang

學習 自 於 http://blog.csdn.net/Elenal/article/details/51493510

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
        <form action="" name="theform">
                <select name="province" onchange="getCity()">
                    <option value = "0">請選擇所在的省份</option>
                    <option value="1">浙江省</option>
                    <option value="2">山東省</option>
                    <option value="3">廣東省</option> 
                    <option value="4">甘肅省</option> 
                </select>
        
                <select id="city" onchange="getQu()">
                    <option value = "0">請選擇所在的城市</option>
                </select>
        
                <select name = "qu">
                    <option value = "0">請選擇所在的縣區</option>
                </select>
        
        </form>
        
    <script>
    
//按照省份的下拉列表的順序定義二維數組  將城市列表對應到省份下
var city=[
        ["杭州市","溫州市","寧波市","紹興市"],//浙江省
        ["濟南市","青島市","濟寧市","濰坊市"],//山東省
        ["廣州市","潮陽","澄海","潮州"],//廣東省
        ["蘭州市","白銀","敦煌","定西"]//甘肅省
    ];

    //縣區數組
    var qu=[
        [
                ["杭州一區","杭州二區"],
                ["溫州一區","溫州二區"],
                ["寧波一區","寧波二區"],
                ["紹興一區","紹興二區"]
        ],

        [
                ["濟南一區","濟南二區"],
                ["青島一區","青島二區"],
                ["濟寧一區","濟寧二區"],
                ["濰坊一區","濰坊二區"],
        ],

        [
                ["廣州一區","廣州二區"],
                ["潮陽一區","潮陽二區"],
                ["澄海一區","澄海二區"],
                ["潮州一區","潮州二區"],
        ],

        [
                ["蘭州一區","蘭州二區"],
                ["白銀一區","白銀二區"],
                ["敦煌一區","敦煌二區"],
                ["定西一區","定西二區"],
        ]

    ];
    var getProvince = document.forms[‘theform‘].province;
    var City = document.forms[0].city;
    var Qu = document.forms[0].qu;
    function getCity(){
        // 初始化
        Qu.length = 1;
        City.length = 1;
        // 獲得 省份選擇的項(索引值,0開始)
        var getSelectIndex = getProvince.selectedIndex;
        // 匹配選擇省下面的 市區
        var proCity = city[getSelectIndex-1]; // 
        console.log( proCity)
        for( var i=0; i<proCity.length; i++){
            City[i+1] = new Option(proCity[i],getSelectIndex)
        }
    }

    function getQu(){
        var getSelectIndex = getProvince.selectedIndex;  // 省
        var getCitySelectedIndex = City.selectedIndex; // 市
        console.log( getCitySelectedIndex )
        var cityQu = qu[getSelectIndex - 1][ getCitySelectedIndex - 1];
        console.log( cityQu )

        for( var i=0; i<cityQu.length; i++){
            Qu[i+1] = new Option(cityQu[0],getCitySelectedIndex)
        }
    }
</script>

原生js實現三級聯動