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