您的位置:首页 > Web前端 > JavaScript

JavaScript省级联动

2016-08-05 16:44 288 查看
省:<select id="pro"><option value="">请选择省</option>

<option value="1">北京</option>

<option value="2">上海</option>

<option value="3">广西</option></select>

市:<select id="city"><option value="">请选择市</option></select>

<script>

    //市数据结构,为json数组对象。数组小标为省的id,数组项为市json数据。如果还有县的联动,同理生成arrTown即可。

    var arrCity = [];

    arrCity[1] = [{ t: '北京市', id: 1}];

    arrCity[2] = [{ t: '上海市', id: 2}];

    arrCity[3] = [{ t: '南宁市', id: 3 }, { t: '桂林市', id: 4 }, { t: '柳州市', id: 5}];

    document.getElementById('pro').onchange = function () {

        addOptions(document.getElementById('city'), arrCity[this.value]);

    }

    function addOptions(s, arr, initValue) {

        if (!arr || arr.length == 0) arr = [{ t: '请选择市', id: ''}];

        if (!s) { alert('select对象不存在!'); return false }

        s.options.length = 0;

        var selectedIndex = 0;

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

            s.options.add(new Option(arr[i].t, arr[i].id));

            if (arr[i].id == initValue) selectedIndex = i;

        }

    }

</script>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  javascript