我已经设法用 json 对象填充我的下拉菜单,效果很好。 目前,我正在尝试根据从下拉列表中选择的选项来显示隐藏 div 中的图像。由于下拉列表由 json 对象填充,我将如何检索图像数据。
HTML
<form>
<fieldset id="autoHeight">
<legend>pod</legend>
<h2>Cars</h2>
<select name="drop_down" id="dropDownCars">
<option value="None" selected="Selected">Select type</option>
</select>
</fieldset>
</form>
<div id="showBmw" class="hidden">
<a href="http://cdn.iphoneincanada.ca/wp-content/uploads/2012/08/white-bmw.jpg"></a>
</div>
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("<option>" + value.carsName + "</option>");
});
});
});
jfiddle 中的任何工作示例,将不胜感激!谢谢。
最佳答案
尝试这段代码... jsfiddle 它解释了在哪里放置代码以根据所选的下拉列表 ID 选择图像
HTML代码
<select id="dropDownDest">
</select>
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($('<option></option>').val(value.carID).html(value.CarType));
});
$('#dropDownDest').change(function () {
alert($(this).val());
//Code to select image based on selected car id
});
关于jquery - 使用 json 对象填充下拉菜单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18484762/