使用json对象填充下拉列表

我已经设法使用json对象填充我的下拉菜单,该工作正常。 目前我正在尝试根据从下拉列表中选择的选项显示隐藏div中的图像。 由于json对象填充了下拉列表,我将如何检索图像数据。

HTML

pod

Cars

Select type

JSON文件

 { Cars: [{ "CarType": "BMW", "carID": "bmw123" }, { "CarType": "mercedes", "carID": "merc123" }, { "CarType": "volvo", "carID": "vol123r" }, { "CarType": "ford", "carID": "ford123" }] } 

这是我使用jquery填充下拉菜单的方法。

 $(document).ready(function() { $.getJSON("../cars.json", function(obj) { $.each(obj.cars, function(key, value) { $("#dropDownCars").append("" + value.carsName + ""); }); }); }); 

jfiddle中的任何工作示例都将非常感谢! 谢谢。

 $('#dropDownDest').on('change', function() { if ($(this).val() == 'vol123r') { $('#imghide').removeClass('hide'); } else { $('#imghide').addClass('hide'); } }); 

FIDDLE DEMO

尝试这段代码…. jsfiddle它解释了根据所选的下拉ID将代码放到哪里选择图像的位置

Html代码

   

jQuery document.ready代码

  var a = { Cars: [{ "CarType": "BMW", "carID": "bmw123" }, { "CarType": "mercedes", "carID": "merc123" }, { "CarType": "volvo", "carID": "vol123r" }, { "CarType": "ford", "carID": "ford123" }] }; $.each(a.Cars, function (key, value) { $("#dropDownDest").append($('').val(value.carID).html(value.CarType)); }); $('#dropDownDest').change(function () { alert($(this).val()); //Code to select image based on selected car id }); 

演示

试试这个代码..

 var obj={ Cars: [ { "CarType": "BMW", "carID": "bmw123" }, { "CarType": "mercedes", "carID": "merc123" }, { "CarType": "volvo", "carID": "vol123r" }, { "CarType": "ford", "carID": "ford123" } ] }; for(var i=0;i').text(obj.Cars[i]['CarType']); $('select').append(option); }