jQuery简单实现省市二级联动示例

2017-08-20  本文已影响1022人  幻凌风
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8" />
    <title></title>
    <script src="script/jquery-3.2.1.js"></script>
    <script>
        //示例数据可从数据库获得
        var datas = {
            "北京": ["朝阳", "海淀", "昌平", "丰台"],
            "山东": ["青岛", "济南", "烟台"],
            "陕西": ["西安", "咸阳", "宝鸡", "延安"],
            "河北": ["石家庄", "张家口", "保定"],
            "河南": ["驻马店", "开封", "郑州","洛阳"],
        };
        $(function () {
            //创建省的selectProvince
            var selectProvince = $("<select id='selectProvince'></select>");
            selectProvince.appendTo($("body"));
            //遍历集合
            $.each(datas, function (key, value) {
                //根据数据创建option并追加到select上
                var option = $("<option value=" + key + ">" + key + "</option>");
                option.appendTo(selectProvince);
            });

            //为省的selectProvince绑定change事件
            selectProvince.change(function () {
                var province = $(this).val();
                //找到市的信息
                var citys = datas[province];
                //删除原来市的信息
                $("#selectCity").empty();
                //添加option
                $.each(citys, function (index, item) {
                    var newCityOption = $("<option>" + item + "</option>");
                    newCityOption.appendTo($("#selectCity"));
                });
            });

            //创建市的selectCity
            var selectCity = $("<select id='selectCity'></select>");
            selectCity.appendTo($("body"));
            //获取选中的省信息
            var pro = $("#selectProvince").val();
            //将省名称作为键到集合中获取值
            var citys = datas[pro];
            //遍历市的数组
            $.each(citys, function (index, item) {
                var option = $("<option value=" + item + ">" + item + "</option>");
                option.appendTo(selectCity);
            })
        });
    </script>
</head>
<body>

</body>
</html>
上一篇 下一篇

猜你喜欢

热点阅读