首页 前端知识 jquery实现联动效果 (通用)省市的三级联动 四级联动 同样的做法

jquery实现联动效果 (通用)省市的三级联动 四级联动 同样的做法

2024-07-27 22:07:44 前端知识 前端哥 685 921 我要收藏

后台 数据格式(树结构 )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;
// 将一级类别添加到select中
$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;
// 将二级类别填写到select中
$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) {
//三级类别名称填写到select中
let threeCategoryName= value.label;
let threeCategoryId = value.id;
// 将该城市对应的区级名称添加到对应的select元素中
$threeCategory.append(`<option value="${threeCategoryId}">${threeCategoryName}</option>`);
});
}
});
});
});
})
let $firstCategory = $("#first-category");
let $secondCategory = $("#second-category");
let $threeCategory = $("#three-category");
复制

效果图效果图

转载请注明出处或者链接地址:https://www.qianduange.cn//article/14404.html
标签
评论
发布的文章

JQuery中的load()、$

2024-05-10 08:05:15

大家推荐的文章
会员中心 联系我 留言建议 回顶部
复制成功!