如何用JS实现基于JSON数据的三级联动下拉选择框?
实现三级联动下拉选择框的方案
步骤1:编写HTML结构
创建三个下拉选择框,通过ID标识方便JavaScript获取操作:
<select id="typeSelect"> <option value="">请选择类型</option> </select> <select id="foodSelect"> <option value="">请先选择类型</option> </select> <select id="specieSelect"> <option value="">请先选择食物</option> </select>
步骤2:准备数据源
直接使用你提供的三个JSON数据集:
// 类型数据集 const typeData = [ { "id": 0, "title": "fruit" }, { "id": 1, "title": "vegetables" }, { "id": 2, "title": "meat" } ]; // 食物数据集 const foodData = [ { "id": 0, "title": "apple", "typeId": 0 }, { "id": 1, "title": "strawberry", "typeId": 0 }, { "id": 2, "title": "chicken", "typeId": 2 }, { "id": 3, "title": "beef", "typeId": 2 } ]; // 品种数据集 const specieData = [ { "id": 0, "titre": "green", "foodId": 0 }, { "id": 1, "titre": "red", "foodId": 1 } ];
步骤3:编写联动逻辑
通过监听下拉框的change事件,根据选中值过滤对应数据集并更新下拉选项:
// 获取DOM元素 const typeSelect = document.getElementById('typeSelect'); const foodSelect = document.getElementById('foodSelect'); const specieSelect = document.getElementById('specieSelect'); // 初始化类型下拉框 function initTypeSelect() { typeData.forEach(type => { const option = document.createElement('option'); option.value = type.id; option.textContent = type.title; typeSelect.appendChild(option); }); } // 根据选中类型更新食物下拉框 function updateFoodSelect(typeId) { // 清空现有选项并添加默认提示 foodSelect.innerHTML = '<option value="">请选择食物</option>'; if (!typeId) { specieSelect.innerHTML = '<option value="">请先选择类型</option>'; return; } // 过滤对应typeId的食物数据 const filteredFoods = foodData.filter(food => food.typeId === parseInt(typeId)); filteredFoods.forEach(food => { const option = document.createElement('option'); option.value = food.id; option.textContent = food.title; foodSelect.appendChild(option); }); // 重置品种下拉框 specieSelect.innerHTML = '<option value="">请先选择食物</option>'; } // 根据选中食物更新品种下拉框 function updateSpecieSelect(foodId) { // 清空现有选项并添加默认提示 specieSelect.innerHTML = '<option value="">请选择品种</option>'; if (!foodId) return; // 过滤对应foodId的品种数据 const filteredSpecies = specieData.filter(specie => specie.foodId === parseInt(foodId)); filteredSpecies.forEach(specie => { const option = document.createElement('option'); option.value = specie.id; option.textContent = specie.titre; specieSelect.appendChild(option); }); } // 绑定事件监听 typeSelect.addEventListener('change', () => { updateFoodSelect(typeSelect.value); }); foodSelect.addEventListener('change', () => { updateSpecieSelect(foodSelect.value); }); // 页面加载完成后初始化类型下拉框 window.addEventListener('DOMContentLoaded', initTypeSelect);
功能说明
- 页面加载完成后,第一个下拉框自动填充所有类型选项
- 选择类型后,第二个下拉框仅展示对应
typeId的食物选项,同时重置第三个下拉框 - 选择食物后,第三个下拉框仅展示对应
foodId的品种选项
内容的提问来源于stack exchange,提问作者Eileen Balaguer
相关产品推荐
相关产品推荐

