省市联动Demo

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
    <title></title>
    <script src="scripts/jquery-1.7.1.js"></script>
    <script>
        //$.each(obj,fun(i,n))
        //如果obj是数组,则i是索引,n是元素
        //如果obj是对象或键值对,i是键,n是值

        //定义省市数据,键值对集合
        var datas = {
            "北京": ["朝阳", "海淀", "昌平", "丰台"],
            "山东": ["青岛", "济南", "烟台"],
            "山西": ["大同", "太原", "运城", "长治"],
            "河南": ["洛阳", "开封", "郑州", "驻马店"],
            "河北": ["石家庄", "张家口", "保定"]
        };
        $(function () {
            //创建省的select
            var select = $('<select id="selectProvince"></select>');
            //追加到body中
            select.appendTo('body');
            //遍历集合
            $.each(datas, function (key, value) {
                $('<option>' + key + '</option>').appendTo(select);
            });

            //创建市的select
            var selectCity = $('<select id="selectCity"></select>');
            selectCity.appendTo('body');

            //获取选中的省信息
            var pro = $('#selectProvince').val();
            //将省名称作为键到集合中获取值
            var citys = datas[pro];
            //遍历市的数组
            $.each(citys, function (index,item) {
                $('<option>' + item + '</option>').appendTo(selectCity);
            })
            //最后写change事件:为省的select绑定change事件
            select.change(function () {
                var citys = datas[$(this).val()];
                //删除市的原有option
                selectCity.empty();
                $.each(citys, function (index, item) {
                    $('<option>' + item + '</option>').appendTo(selectCity);
                })
            })
        })
    </script>
</head>
<body>
    
</body>
</html>

转载于:https://www.cnblogs.com/wyt007/p/6049992.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值