我有一个从JSON数据填充的动态表。我希望每列都有一个选择下拉列表。列数不固定。它们由JSON填充。所以我希望每列顶部的选择下拉列表。此下拉列表也应由JSON填充。
HTML:
<table id="jsonTable" class="table table-hovere">
</table>
Jquery的:
function addAllColumnHeaders(myList) {
var columnSet = [];
var headerTr$ = $('<tr/>');
for (var i = 0; i < myList.length; i++) {
var rowHash = myList[i];
for (var key in rowHash) {
if ($.inArray(key, columnSet) == -1) {
columnSet.push(key);
headerTr$.append($('<th/>').html(key));
}
}
}
$("#jsonTable").append(headerTr$);
return columnSet;
}
$.getJSON("data.json", function (data) {
var columns = addAllColumnHeaders(data);
for (var i = 0; i < data.length; i++) {
var row$ = $('<tr/>');
for (var colIndex = 0; colIndex < columns.length; colIndex++) {
var cellValue = data[i][columns[colIndex]];
if (cellValue == null) { cellValue = ""; }
row$.append($('<td/>').html(cellValue));
}
$("#jsonTable").append(row$);
}
});
JSON:
[
{
"Model": "Iphone 18",
"Name": "iOS",
"Share": 57.56,
"Price Range": "$800 - $1000",
"Brand": "Apple"
},
{
"Model": "Nexus 23",
"Name": "Android",
"Share": 24.66,
"Price Range": "$600 - $800",
"Brand": "Samsung"
},
{
"Model": "Tom-tom",
"Name": "Java ME",
"Share": 10.72,
"Price Range": "$200 - $900",
"Brand": "X Brand"
}
]
请帮助。提前谢谢。
答案 0 :(得分:1)
你可以这样做 -
https://jsfiddle.net/9eemmbjc/1/
你的json
var jsonResult=[
{
"Model": "Iphone 18",
"Name": "iOS",
"Share": 57.56,
"Price Range": "$800 - $1000",
"Brand": "Apple"
},
{
"Model": "Nexus 23",
"Name": "Android",
"Share": 24.66,
"Price Range": "$600 - $800",
"Brand": "Samsung"
},
{
"Model": "Tom-tom",
"Name": "Java ME",
"Share": 10.72,
"Price Range": "$200 - $900",
"Brand": "X Brand"
}
]
<强>的jQuery 强>
var rowArray = new Array();
$.each(jsonResult,function(index,item){
row=$("<tr/>");
row.prepend('<td><select><option>Some option</select></td>');
$.each(item,function(inx,el){
$(row).append('<td>'+el+'</td>');
});
rowArray.push(row);
})
$('table').html(rowArray);
<强>更新强>
https://jsfiddle.net/9eemmbjc/2/
不是一个好方法,但应该从jsonObject做你想做的事。
我在脚本中更改了一些内容,用于在标题之前显示顶部的选择框行。
var selectRow= {
Model:$('<select/>'),
Name:$('<select/>'),
Share:$('<select/>'),
PriceRange:$('<select/>'),
Brand:$('<select/>')
};
//select boxes at the top
$.each(jsonResult,function(index,item){
selectRow.Model.append('<option>'+item.Model+'</option>');
selectRow.Name.append('<option>'+item.Name+'</option>');
selectRow.Share.append('<option>'+item.Share+'</option>');
selectRow.PriceRange.append('<option>'+item["Price Range"]+'</option>');
selectRow.Brand.append('<option>'+item.Brand+'</option>');
});
var dropdownRow= '<tr><th>'+selectRow.Model[0].outerHTML+'</th><th>'+selectRow.Name[0].outerHTML+'</th><th>'+selectRow.Share[0].outerHTML+'</th><th>'+selectRow.PriceRange[0].outerHTML+'</th><th>'+selectRow.Brand[0].outerHTML+'</th></tr>'