我有一个问题我托盘使用jquery创建一组json选择。我不太明白如何实现并获得带有json
的循环的标签选项{
"listOfOptions" : [
{
"Option1" : [
{
"id": "1",
"name": "Pine"
},
{
"id": "a02",
"name": "Birch"
}
],
"Option2" : [
{
"id": "a01",
"name": "Pine"
},
{
"id": "a02",
"name": "Birch"
}
],
"Option3" : [
{
"id": "a01",
"name": "Pine"
},
{
"id": "a02",
"name": "Birch"
}
]
}
]
}
我正试图找到一种方法来创建一个循环,让我从这个json中获取Selects的标签和选项
$.ajax({
url: 'data/data.json',
dataType:'JSON',
success: function(listOfOptions {
$.each(listOfOptions, function(key, item) {
$.each(item, function(i, val) {
alert(val);
})
}
}
});
答案 0 :(得分:0)
这样的事情怎么样:
$.each(listOfOptions.listOfOptions[0],function(k,v) {
var optHTML = $('<label/>', {text:k + ': '}).append( $('<select/>') ).append( '<br/>' );
$.each(v, function(key,value) {
optHTML.find('select').append( $('<option/>',{value:value.id,text:value.name}) );
});
$('body').append( optHTML );
});
var listOfOptions = {
"listOfOptions" : [
{
"Option1" : [
{
"id": "1",
"name": "Pine"
},
{
"id": "a02",
"name": "Birch"
}
],
"Option2" : [
{
"id": "a01",
"name": "Pine"
},
{
"id": "a02",
"name": "Birch"
}
],
"Option3" : [
{
"id": "a01",
"name": "Pine"
},
{
"id": "a02",
"name": "Birch"
}
]
}
]
};
$.each(listOfOptions.listOfOptions[0],function(k,v) {
var optHTML = $('<label/>', {text:k + ': '}).append( $('<select/>') ).append( '<br/>' );
$.each(v, function(key,value) {
optHTML.find('select').append( $('<option/>',{value:value.id,text:value.name}) );
});
$('body').append( optHTML );
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>