这类文章本来懒得写语言描述,但是博客园有字数限制还是写一两句,临时项目不做优化有Bug请自理嘿嘿。直接上代码
第一个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("") }) var html = ""; $.each(data,function(i,item){ html+= ''; }) $("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 上个图片玩玩