多级联动的另类实现 - 纯忽悠贴

这类文章本来懒得写语言描述,但是博客园有字数限制还是写一两句,临时项目不做优化有Bug请自理嘿嘿。直接上代码

第一个select中默认填充数据

<select name="region" class="form-control" data-depth="1">
    <option value="0">--请选择--</option>
    @foreach (var tree in Model.RootTree)
    {
        <option value="@tree.Id">@tree.Name</option>
    }
</select>
<select name="region" class="form-control" data-depth="2">
    <option value="0">--请选择--</option>
</select>
<select name="region" class="form-control" data-depth="3">
    <option value="0">--请选择--</option>
</select>

js代码

 var treePath = @Html.Raw(Model.TreePath);
    var url = "/Component/AjaxRegion";

    $(function () {
        if (treePath.length > 0){
            $.each(treePath, function (i, item) {
                $("select[name=region]").eq(i).val(item.Region_Id);  
                getRegion(item.Region_Id,i+1)
            })
        }

        $("select[name=region]").change(function(){
            var pid = $(this).val();
            var flag = parseInt($(this).attr("data-depth"));
            getRegion(pid,flag);
        });
    });

    function getRegion(pid,flag){
     
        $.ajax({
            type: "GET",
            url: url,
            async: false,
            data: "pid=" + pid,
            dataType: "json",
            success: function (data) {
                
                var selects = $("select[name=region]");
                $.each(selects,function(i,item){
                    var depth = parseInt($(item).attr("data-depth"));
                    if(depth > flag)
                        $(item).html("<option value=\"0\">--请选择--</option>")
                })

                var html = "";
                $.each(data,function(i,item){
                    html+= '<option value="'+item.Id+'">'+ item.Name +'</option>';
                })
                $("select[name=region]").eq(flag).append(html);
               
            }
        })
    }

这里说明下 var treePath = @Html.Raw(Model.TreePath); 我是后台直接生成数据格式如下

 var treePath = [{"Region_Id":1,"Name":"北京市","Parent_Id":3523},{"Region_Id":35,"Name":"市辖区","Parent_Id":1},{"Region_Id":379,"Name":"东城区","Parent_Id":35}];

功能都ok 上个图片玩玩

转载于:https://www.cnblogs.com/okzhangning/p/5422992.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值