jQuery 使用 json 对象填充下拉列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18484762/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Populating drop down with json object
提问by user2721700
I have managed to populate my drop down menu with a json object, which worked fine. Currently I am trying to display an image which is in a hidden div based on an option selected from the drop down. As the drop down is populated by the json object how would I retrieve the image data.
我设法用一个 json 对象填充我的下拉菜单,效果很好。目前,我正在尝试根据从下拉列表中选择的选项显示隐藏 div 中的图像。由于下拉列表由 json 对象填充,我将如何检索图像数据。
Html
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 File
JSON 文件
{
Cars: [{
"CarType": "BMW",
"carID": "bmw123"
}, {
"CarType": "mercedes",
"carID": "merc123"
}, {
"CarType": "volvo",
"carID": "vol123r"
}, {
"CarType": "ford",
"carID": "ford123"
}]
}
This is how I populate the dropdown menu using jquery.
这就是我使用 jquery 填充下拉菜单的方式。
$(document).ready(function() {
$.getJSON("../cars.json", function(obj) {
$.each(obj.cars, function(key, value) {
$("#dropDownCars").append("<option>" + value.carsName + "</option>");
});
});
});
Any working example in jfiddle, would be very much appreciated! Thanks.
jfiddle 中的任何工作示例,将不胜感激!谢谢。
采纳答案by RONE
$('#dropDownDest').on('change', function() {
if ($(this).val() == 'vol123r') {
$('#imghide').removeClass('hide');
} else {
$('#imghide').addClass('hide');
}
});
回答by iJade
Try this piece of code....jsfiddleit explains where to put the code to select image based on the selected drop down id
试试这段代码.... jsfiddle它解释了在哪里放置代码以根据选定的下拉 id 选择图像
Html code
html代码
<select id="dropDownDest">
</select>
jQuery document.ready code
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
});
回答by Prabu Parthipan
Try this code..
试试这个代码..
var obj={
Cars: [
{
"CarType": "BMW",
"carID": "bmw123"
},
{
"CarType": "mercedes",
"carID": "merc123"
},
{
"CarType": "volvo",
"carID": "vol123r"
},
{
"CarType": "ford",
"carID": "ford123"
}
]
};
for(var i=0;i<obj.Cars.length;i++)
{
var option=$('<option></option>').text(obj.Cars[i]['CarType']);
$('select').append(option);
}