jqはjsonデータに基づいて、動的に2級連動メニューを生成する

11738 ワード

jqはjsonデータに基づいて、動的に2級連動メニューを生成する
  • html
  • jsonデータ
  • jqサイクル
  • 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 = `">${item.name}`;
    	$('#vegetable').append(html)
    }
    $('#vegetable').change(function(){
    	//        ,         
    	$('#fruit').html('');
    	//   :       value
    	let index = $(this).val() - 1;
    	if(index < 0){
    		return;
    	}
    	//   value       food
    	for(let item of menu[index].food){
    		let	html = `">${item.name}`;
    		$('#fruit').append(html)
    	}
    })