let menu =[{"type_id":1,"name":"蔬菜","food":[{"food_id":1,"name":"白菜","price":"10"},{"food_id":2,"name":"冬瓜","price":"10"},{"food_id":3,"name":"西藍花","price":"10"}]},{"type_id":2,"name":"水果","food":[{"food_id":4,"name":"香蕉","price":"10"},{"food_id":5,"name":"蘋果","price":"10"},{"food_id":6,"name":"橙子","price":"10"}]}];
jq循環
// 根據menu的數據,動態生成一個二級聯動菜單for(let item of menu){let html =`<option value="${item.type_id}">${item.name}</option>`;$('#vegetable').append(html)}$('#vegetable').change(function(){// 每次改變選擇時,應先清空二級下拉框$('#fruit').html('<option value="0">請選擇類別二</option>');// 重點:獲取當前選擇的valuelet index =$(this).val()-1;if(index <0){return;}// 根據value去循環相對應的foodfor(let item of menu[index].food){let html =`<option value="${item.food_id}">${item.name}</option>`;$('#fruit').append(html)}})