后台 数据格式(树结构 )Java构建树形结构 Cascader 级联选择器

html
| <div class="col-md-6"> |
| <select id="first-category"> |
| <option value="">请选择一级类别</option> |
| </select> |
| <select id="second-category"> |
| <option value="">请选择</option> |
| </select> |
| <select id="three-category"> |
| <option value="">---</option> |
| </select> |
| </div> |
复制
js categoriesValue 是后端传过来的数据
| $(function () { |
| console.log(categoriesValue) |
| $.each(categoriesValue, function (index, obj) { |
| let firstCategoryName = obj.label; |
| let firstCategoryId = obj.id; |
| |
| $firstCategory.append( |
| `<option value="${firstCategoryId}">${firstCategoryName}</option>` |
| ); |
| }) |
| $firstCategory.change(function () { |
| |
| $secondCategory.empty(); |
| $secondCategory.append(`<option value="">---</option>`); |
| |
| let firstElementCategoryName = $(this).children("option:selected").text(); |
| $.each(categoriesValue, function (index, obj) { |
| |
| let firstCategoryName = obj.label; |
| |
| if (firstElementCategoryName === firstCategoryName) { |
| |
| let secondCategories = obj.children; |
| |
| $.each(secondCategories, function (index, obj) { |
| |
| let secondCategoryName = obj.label; |
| let secondCategoryId = obj.id; |
| |
| $secondCategory.append( |
| `<option value="${secondCategoryId}">${secondCategoryName}</option>` |
| ); |
| }); |
| } |
| }); |
| }); |
| |
| $secondCategory.change(function () { |
| |
| $threeCategory.empty(); |
| $threeCategory.append(`<option value="">---</option>`); |
| |
| let secondElementCategoryName = $(this).children("option:selected").text(); |
| $.each(categoriesValue, function (index, obj) { |
| |
| let secondCategories = obj.children; |
| $.each(secondCategories, function (index, cityObj) { |
| |
| let secondCategoryName = cityObj.label; |
| if (secondElementCategoryName === secondCategoryName) { |
| |
| let threeCategories = cityObj.children; |
| |
| $.each(threeCategories, function (index, value) { |
| |
| let threeCategoryName= value.label; |
| let threeCategoryId = value.id; |
| |
| $threeCategory.append(`<option value="${threeCategoryId}">${threeCategoryName}</option>`); |
| }); |
| } |
| }); |
| }); |
| }); |
| }) |
| |
| let $firstCategory = $("#first-category"); |
| let $secondCategory = $("#second-category"); |
| let $threeCategory = $("#three-category"); |
复制
效果图