zoukankan      html  css  js  c++  java
  • 多级联动的另类实现

    这类文章本来懒得写语言描述,但是博客园有字数限制还是写一两句,临时项目不做优化有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 上个图片玩玩

  • 相关阅读:
    (转)程序员应该知道的10个eclipse调试技巧
    Hibernate缓存
    【转】Hibernate 原汁原味的四种抓取策略
    hibernate 延迟加载和抓取策略
    移动端接口安全
    Thinkphp3.2.3中的RBAC权限验证
    单例模式--工厂模式
    php爬虫入门
    php爬虫入门
    .htaccess使用方法介绍
  • 原文地址:https://www.cnblogs.com/okzhangning/p/5422992.html
Copyright © 2011-2022 走看看