jq根據json數據,動態生成一個二級聯動菜單

jq根據json數據,動態生成一個二級聯動菜單

html

蔬菜:<select name="vegetable" id="vegetable">
			<option value="0">請選擇類別一</option>
		</select>
水果:<select name="fruit" id="fruit">
		<option value="0">請選擇類別二</option>
	</select>

json數據

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>');
	// 重點:獲取當前選擇的value
	let index = $(this).val() - 1;
	if(index < 0){
		return;
	}
	// 根據value去循環相對應的food
	for(let item of menu[index].food){
		let	html = `<option value="${item.food_id}">${item.name}</option>`;
		$('#fruit').append(html)
	}
})
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章